Python自动完成用户输入

时间:2014-01-07 13:03:15

标签: python string printing autocomplete sentence

我有一个团队名单。让我们说他们是

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

在程序中,我问用户他想要做哪些团队。我想让python自动填充用户的输入,如果它与团队匹配并打印出来的话。

因此,如果用户写“Bla”并按输入,布莱克本团队应自动打印在该空间中并用于其余代码。所以例如;

您的选择:Bla(用户写“Bla”并按输入

它应该是什么样的

你的选择:布莱克本(该计划完成其余部分)

2 个答案:

答案 0 :(得分:2)

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]

答案 1 :(得分:0)

这取决于你的用例。如果您的程序是基于命令行的,那么至少可以使用readline模块并按 TAB 来执行此操作。这个链接也提供了一些很好解释的例子,因为它的Doug Hellmanns PyMOTW。如果您通过GUI尝试,则取决于您使用的API。在这种情况下,您需要提供更多详细信息。