gpt4 book ai didi

python - Python 中的字符串等价/比较

转载 作者:太空宇宙 更新时间:2023-11-04 08:19:18 26 4
gpt4 key购买 nike

我似乎无法在 python 中正确比较字符串,在 if 条件下比较它的正确方法是什么?

Testfile = "test.txt"
with open(TestFile) as testSet:
line = testSet.read().rstrip('\n')
if "#*#*# ham" or "#*#*# spam" in line:
print line

我的 test.txt 看起来像这样:

#*#*# ham
foo bar bar foo bar bar bar bar
#*#*# ham
foo bar bar foo bar foo bar foo foo bar bar
#*#*# spam
foo bar foo foo bar barfoo bar foo foo bar bar
#*#*# spam
foo bar foo foo bar bar foo foo bar bar
#*#*# ham
foo bar foo foo
#*#*# spam
foo bar foo foo bar bar foo foo bar bar
#*#*# spam
bar foo bar foo foo bar
#*#*# spam
bar bar foo foo

最佳答案

做:

Testfile = "test.txt"
with open(TestFile) as testSet:
for line in testSet:
line = line.strip()
if "#*#*# ham" in line or "#*#*# spam" in line:
print line

而不是你在做什么。您正在将整个文件读入 line 变量,就像您的代码一样。

关于python - Python 中的字符串等价/比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8541570/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com