【问题标题】:Print the name of the first letter inputted by user - Python打印用户输入的第一个字母的名称 - Python
【发布时间】:2016-12-21 18:23:14
【问题描述】:
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)

我有这个,我的 .txt 文件有点长,显示的错误是 - “IndexError:字符串索引超出范围”。 我怎样才能让它发挥作用?

【问题讨论】:

  • 大胆猜测:您的文本文件有一个空行,可能在最后。删除它。
  • 欢迎来到 StackOverflow。请阅读并遵循帮助文档中的发布指南。 Minimal, complete, verifiable example 适用于此。在您发布代码并准确描述问题之前,我们无法有效地帮助您。您发布的代码不足以重现问题。
  • @Kevin 如何删除它们? (我有 2 个空行)
  • @roganjosh 谢谢!!

标签: python arrays string list


【解决方案1】:

您可以结合多种因素对列表理解进行小幅编辑。

  1. 空的东西是虚假的,例如列表/字典/空字符串

    bool('')

    Out[1]: False

    bool('a')

    Out[2]: True

  2. 逻辑运算符and 将短路。这意味着在这种情况下,如果它在第一次测试中看到 False,它将不会尝试后续测试。

放在一起,我们可以避免尝试索引空字符串。

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

【讨论】:

    【解决方案2】:

    只是做:

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

    【讨论】:

    • 我设法解决了这个问题。现在我有一个 GUI 登录,我正在尝试将它附加到主程序
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-01-21
    • 1970-01-01
    • 2022-08-23
    • 1970-01-01
    • 2012-09-13
    • 2023-02-09
    • 1970-01-01
    相关资源
    最近更新 更多