2011-12-16 12 views
1

我似乎無法在python中正確比較字符串,在if條件下比較它的正確方法是什麼?在Python中的字符串等效/比較

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 

回答

4

務必:

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 

而不是你在做什麼。您正在將整個文件讀入行變量,代碼的方式。

2

這被解讀爲:

if ("#*#*# ham") or ("#*#*# spam" in line): 

和字符串被強制轉換爲真實的。

嘗試:

if "#*#*# ham" in line or "#*#*# spam" in line: 
+0

該條件也打印出'foo bar'文本行 – alvas 2011-12-17 00:08:08

+0

'if *#*#ham#'行或######spam#行中:`條件結束始終爲真。 – alvas 2011-12-17 00:09:01

+1

剛剛測試過,我應該在之前抓到這個......正如jsbueno所說,你的整個文件內容都是一致的,而不是單獨的行。 – Corbin 2011-12-17 00:15:44

0

這應該閱讀:

testfile = "test.txt" 
with open(testFile) as f: 
    for line in f: 
     line = line.rstrip() 
     if "#*#*# ham" in line or "#*#*# spam" in line: 
      print line 

另外一個不錯的形式是:

if any(substr in line for substr in (#*#*# ham", "#*#*# spam")): 
    print line