Python 字符串比较与从文件中读取的行不匹配 [英] Python string comparison not matching a line read from a file

查看:32
本文介绍了Python 字符串比较与从文件中读取的行不匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

^^^^^^^^^ 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

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

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

我也试过 is 而不是 ==(但没想到它会起作用,结果没有).

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

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

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

寻找方向和解释.

推荐答案

在行尾可能有换行符或其他空格,所以 == 将不起作用,除非你先修剪一下:

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

这篇关于Python 字符串比较与从文件中读取的行不匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆