pythontext-filesline-by-line

Python string comparison not matching a line read from a file


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.


Solution

  • 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() == "^^^^^^^^^":