Python autocomplete user input [closed]

你。 提交于 2019-12-21 05:35:14

问题


I have a list of teamnames. Let's say they are

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

In the program I ask the user which team he would like to do stuff with. I want python to autocomplete the user's input if it matches a team and print it.

So if the user writes "Bla" and presses enter, the team Blackburn should automatically be printed in that space and used in the rest of the code. So for example;

Your choice: Bla (User writes "Bla" and presses enter)

What it should look like

Your Choice: Blackburn (The program finishes the rest of the word)


回答1:


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]



回答2:


That depends on your usecase. If your program is commandline based, you can do that at least by using the readline module and pressing TAB. This link also provides some well explained examples on that since its Doug Hellmanns PyMOTW. If you are trying that via a GUI it depends on the API you are using. In that case you need to deliver some more details please.



来源:https://stackoverflow.com/questions/20972367/python-autocomplete-user-input

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!