Python自动完成用户输入 [英] Python autocomplete user input

查看:580
本文介绍了Python自动完成用户输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

在程序中,我问用户他想和哪个团队一起工作.我希望python如果与团队匹配则自动完成用户的输入并打印出来.

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.

因此,如果用户写"Bla"并按 enter ,则Blackburn团队应自动在该空间中打印并在其余代码中使用.例如,

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;

您的选择:Bla(用户写"Bla"并按 enter )

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

应该是什么样子

您的选择:布莱克本(程序将完成单词的其余部分)

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

推荐答案

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]

这篇关于Python自动完成用户输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆