我似乎无法在 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 变量,就像您的代码一样。
