Python自动完成用户inpu

2024-09-23 22:21:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个队名列表。假设他们是

teamnames=["Blackpool","Blackburn","Arsenal"]

在程序中,我问用户他想和哪个团队合作。我想让python自动完成用户的输入,如果它匹配一个团队并打印出来。

因此,如果用户编写“Bla”并按enter,那么团队Blackburn应该自动打印在该空间中,并在其余代码中使用。例如

您的选择:Bla(用户编写“Bla”并按回车键

它应该是什么样子

您可以选择:Blackburn(程序会完成剩下的单词)


Tags: 代码用户程序列表空间团队arsenalenter
2条回答

这取决于你的用例。如果您的程序是基于命令行的,那么至少可以使用readline模块并按TAB来完成这项工作。这个链接也提供了一些很好的例子,因为它的道格赫尔曼PyMOTW。如果你是通过一个GUI来尝试的,那就取决于你使用的API。在这种情况下,你需要提供更多的细节,请。

teamnames=["Blackpool","Blackburn","Arsenal"]

user_input = raw_input("Your choice: ")

# You have to handle the case where 2 or more teams starts with the same string.
# For example the user input is 'B'. So you have to select between "Blackpool" and
# "Blackburn"
filtered_teams = filter(lambda x: x.startswith(user_input), teamnames)

if len(filtered_teams) > 1:
    # Deal with more that one team.
    print('There are more than one team starting with "{0}"'.format(user_input))
    print('Select the team from choices: ')
    for index, name in enumerate(filtered_teams):
        print("{0}: {1}".format(index, name))

    index = input("Enter choice number: ")
    # You might want to handle IndexError exception here.
    print('Selected team: {0}'.format(filtered_teams[index]))

else:
    # Only one team found, so print that team.
    print filtered_teams[0]

相关问题 更多 >