Python: Comparing two strings that should be the same but that are not

python, string

Solution

It's likely that extra spacing is your culprit. You may also try downcasing the string.

SentenceIMLookingfor='blha blha blah'
with open('textfile.lua','r') as my_file:
    for line in my_file:
        if line.lower().strip() == SentenceIMLookingfor:
            #DO_SOMETHING

If, however, you are not checking for a line that is exactly equal to the Sentence you're looking for, you'll want to use the `in` operator to check for equality, so replace the `if` above with

        if SentenceIMLookingfor in line.lower(): # you may not want .lower()

Since there is no need to read the entire file into memory, you can iterate over the lines of the file with `for line in my_file`. `.lower()` converts a string to all lower-case letters, `.strip()` cuts off any preceding or trailing whitespace

As suggested by @SethMMorton in the comments, you can use `enumerate` to iterate with the line numbers `for i, line in enumerate(my_file)`

If you are trying to collect the line numbers that this string appears on (which seems likely) you can accomplish that with a list comprehension

with open('textfile.lua','r') as my_file:
    line_nos = [i for i, line in enumerate(my_file) if line.lower().strip() == SentenceIMLookingfor]

Problem

I'm a noob so I hope this is the right place to ask this question. This is really driving me nuts. I'm looking for a sentence in some text file, here is the partial code: ``` SentenceIMLookingfor='blha blha blah' with open('textfile.lua','r') as my_file: raw_dadat=my_file.read().split('\n') for i in range(1, len(raw_dadat)): if(raw_dadat[i]==SentenceIMLookingfor): DO_SOMETHING ``` Well it doesn't do anything.( And I need to know at what line "SentenceIMLookingfor" is). I've check the ids ( ofc they are not the same so if I use 'is' instead of '==' it won't work). Also I'm sure that the sentence is in my text file, it is even stored in raw_data[210]. I've check the "type" and it's str. Also there are about 3 spaces in the sentence, I don't know if that can help, and "len(raw_dadat)" is more or less equal to 4000. Well I don't see what I'm doing wrong. Thanks a lot in advance!!

Original source