Search code examples
python-3.xtextcase-sensitivecase-insensitive

How to compare string case insensitive


So guys i'am trying to make a dictionary app. I want it to be case-insensitive. Firstly i saw some solutions for this promblem but non of them suited with me. Let me explain it with an example: Let's say i have the word School my code works fine when i search it like School but it doesn't work when i search it like school.

i really didn't get this solution 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")

I want School to be equal to school and scHool and schooL. But in my case School is just equaled to School


Solution

  • If you want to be case-insensitive, you can just convert the input and line into lowercase and compare them.

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