从列表中读取以用户输入的字母开头的行?

2024-04-20 06:05:13 发布

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

注意:一些同学告诉我必须使用userInput来创建另一个基于userInput的列表。(例如:输入“g”,创建以“g”开头的国家列表。)

这是我现在的密码。你知道吗

countries = []
population = []
str = []
path = "E:\\SCRIPTING\\Countries.txt"
obj = open(path, "r")
allList = obj.readlines()
obj.close()
userI = input("Please input a single letter: ")
if userI.isalpha():
    if len(userI) > 1:
        print("Please enter only a single letter.")
    else:
        print("continue")
elif userI.isdigit():
    int(userI)
    print("Please enter a single letter, not a number.")
else:
    print("Please make sure that you enter a single letter.")

到目前为止,我所知道的是,它正在读取我的.txt文件,并在输入错误时显示不同的错误/消息。 (程序将置于else:print(“continue”)下,因为它是我的检查点。你知道吗

程序只接受1个字母,并打印以该字母开头的所有行。你知道吗


Tags: pathtxtobj列表inputifelseprint
2条回答

您可以返回一个带有简单测试的列表,就在您执行以下操作之前:

print("continue")

你可以加上那些线

listToBeDisplayed = [line for line in allList if line.startswith(userI)]
for line in listToBeDisplayed :
    print line

您实际上没有应用主逻辑,您已经正确地完成了输入处理和文件打开。你知道吗

您需要:

else:
    # Bad variable name, see python.org/dev/peps/pep-0008/#id36
    for line in allList
        if line.startswith(userI):
            print line

elif userI.isdigit():

更新:

在查看了更新后的代码之后,我建议再做一个更改:

# raw_input() instead of input()
userI = raw_input("Please input a single letter: ")

除此之外,我还测试了您的代码,只要path所指向的文件中有文本数据,它就可以工作。还有一点需要注意,startswith是区分大小写的,所以请确保将字母表的大小写正确作为文件中的文本。你知道吗

相关问题 更多 >