考慮以下列表循環:的Python爲避免類似的比賽
items = ['about-conference','conf']
遍歷使用for循環打印「有關的會議」下面的列表中和「的conf」
for word in items:
if 'conf' in word:
print word
怎麼辦如果if語句遇到完全匹配,即僅打印「conf」,我會得到if語句只能證明爲真?
謝謝。
考慮以下列表循環:的Python爲避免類似的比賽
items = ['about-conference','conf']
遍歷使用for循環打印「有關的會議」下面的列表中和「的conf」
for word in items:
if 'conf' in word:
print word
怎麼辦如果if語句遇到完全匹配,即僅打印「conf」,我會得到if語句只能證明爲真?
謝謝。
不要使用in
,使用==
來測試確切的平等:
if word == "conf":
print word
試試這個:
for word in list:
if word == 'conf':
print word
你可以做到以下幾點:
for word in list:
if 'conf' == word.strip():
print(word)
地帶保證沒有虛假的字符,如空格或行尾。
不清楚自己想要什麼,但如果你正在尋找這樣的事情,它使用單詞邊界所以它的方式隔開破折號,空格,管柱等開始
import re
for word in items:
if 'conf' in re.findall(r'\b\w+\b', word):
print 'conf'
在這個具體的例子,你可以將其改寫爲:
items = ['about-conference','conf']
if 'conf' in items:
print 'conf'