use*_*412 8 python printing string autocomplete sentence
我有一个团队名称列表。让我们说他们是
teamnames=["Blackpool","Blackburn","Arsenal"]
Run Code Online (Sandbox Code Playgroud)
在程序中,我问用户他想和哪个团队一起做事。如果用户的输入与团队匹配并打印,我希望 python 自动完成用户的输入。
因此,如果用户输入“Bla”并按下enter,则 Blackburn 团队应自动打印在该空间中并在其余代码中使用。例如;
您的选择:Bla(用户输入“Bla”并按下enter)
它应该是什么样子
您的选择:布莱克本(该程序完成了单词的其余部分)
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]
Run Code Online (Sandbox Code Playgroud)