如何比较不区分大小写的字符串

How to compare string case insensitive

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

我真的没有得到这个解决方案

    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 等于 schoolscHool 以及 schooL。但在我的例子中 School 等于 School

如果想不区分大小写,可以将input和line转成小写比较即可。

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")

我认为您可以简单地在搜索字符串上调用 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")