简体   繁体   English

打印用户输入的第一个字母的名称-Python

[英]Print the name of the first letter inputted by user - Python

letter = input("Enter a letter to show that particular country: ")
output_names = [name for name in Country if (name[0] in letter)]
print(output_names)

I have this and my .txt file is bit long and the error showing is- "IndexError: string index out of range". 我有这个,我的.txt文件有点长,显示的错误是-“ IndexError:字符串索引超出范围”。 How can I make it work? 我该如何运作?

You can use a combination of factors to make a small edit to the list comprehension. 您可以使用多种因素组合来对列表理解进行小的编辑。

  1. Empty things are falsey eg lists/dictionaries/empty strings 空的东西是假的,例如列表/字典/空字符串

    bool('')

    Out[1]: False

    bool('a')

    Out[2]: True

  2. The logical operator and will short circuit. 上述逻辑运算器and意愿短路。 That means in this case, if it sees something False on its first test, it will not attempt the subsequent tests. 这意味着在这种情况下,如果它在第一个测试中看到False ,它将不会尝试后续的测试。

Putting it together, we can avoid trying to index the empty string. 放在一起,我们可以避免尝试索引空字符串。

filtered = [item for item in my_list if item and item[0]]
                                     ^^^^^^^
                                     False for empty string

做就是了:

print [name for name in Country if name.lower().startswith(letter.lower())]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM