Python 字符串比较与从文件中读取的行不匹配

alm*_*ner 4 python text-files line-by-line

我有一个文本文件,每行都有关键字,如下所示:

foo
foo1
^^^^^^^^^
foo5
foo7
Run Code Online (Sandbox Code Playgroud)

^^^^^^^^^是一个标志,设置为一旦到达就中断 for 循环:

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
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,第二个条件永远不会满足(**if line == "^^^^^^^^^":**)。

我也尝试is==(但没想到它能起作用,而且没有)。

当我尝试时line.startswith("^^^^^^"):,满足条件,循环结束。我想知道为什么==在上述情况下不起作用。

寻找一些方向和解释。

Ósc*_*pez 5

行尾可能有换行符或其他空格,因此==不起作用,除非您先修剪它:

if line.strip() == "^^^^^^^^^":
Run Code Online (Sandbox Code Playgroud)