Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python string comparison not matching a line read from a file [duplicate]

I have got a text file with keywords in each line like so:

foo
foo1
^^^^^^^^^
foo5
foo7

^^^^^^^^^ is a flag set to break the for loop once reached:

keywords = []
    with open("keywords.txt") as f:
        for line in f:
            if line.startswith(request.GET.get('search', '')):
                keywords.append(line.lower())
            if line == "^^^^^^^^^":
                break

In above code, the second condition is never met (**if line == "^^^^^^^^^":**).

I also tried is instead of == (but did not expect it to work, and it didn't).

When I tried line.startswith("^^^^^^"):, the condition is met, and loop is ended. I'm wondering why == doesn't work in the above case.

Looking for some direction and explanation.

like image 864
almost a beginner Avatar asked Oct 23 '25 18:10

almost a beginner


1 Answers

There probably is a line break or other whitespace at the end of the line, so == won't work, unless you trim it first:

if line.strip() == "^^^^^^^^^":
like image 178
Óscar López Avatar answered Oct 26 '25 06:10

Óscar López