【问题标题】:How to compare string case insensitive如何比较字符串不区分大小写
【发布时间】:2019-01-12 20:39:59
【问题描述】:

所以伙计们,我正在尝试制作一个字典应用程序。我希望它不区分大小写。首先,我看到了一些解决这个问题的方法,但没有一个适合我。让我用一个例子来解释一下:假设我有 School 这个词,当我像 School 那样搜索它时,我的代码可以正常工作,但是当我像 school 那样搜索它时,它就不起作用了。

我真的没有得到这个解决方案https://stackoverflow.com/a/15400311/9692934

    key_to_search = input() #not raw_input() since its python 3    
    with open("fileOfWords.txt") as enter:
        for line in enter:
            if line.startswith("%s" % key_to_search):
                print(key_to_search + " is in the dictionary")

我希望 School 等于 schoolscHoolschooL。但在我的情况下,School 等于 School

【问题讨论】:

  • 所以这不是您要问的 filename 的大小写,而是关于如何比较不区分大小写的字符串?那么您的标题非常具有误导性,因为 open 与它无关。请阅读how to ask good questions,以及this question checklist
  • @Someprogrammerdude 我试图问有没有办法只降低或提高单词中的一个字母。如果答案是否定的,我将全部降低

标签: python-3.x text case-sensitive case-insensitive


【解决方案1】:

如果要不区分大小写,只需将输入和行转换为小写并进行比较即可。

key_to_search = input() #not raw_input() since its python 3    
with open("fileOfWords.txt") as enter:
    for line in enter:
        if line.lower().startswith(key_to_search.lower()):
            print(key_to_search + " is in the dictionary")

【讨论】:

    【解决方案2】:

    我认为您可以简单地在搜索字符串上调用lowerkey_to_search = key_to_search.lower() 并将所有单词保存为小写。您的代码将是:

    key_to_search = input().lower() #not raw_input() since its python 3    
        with open("fileOfWords.txt") as enter:
            for line in enter:
                if line.startswith("%s" % key_to_search):
                    print(key_to_search + " is in the dictionary")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多