【发布时间】:2012-05-28 14:20:52
【问题描述】:
考虑以下列表:
items = ['about-conference','conf']
使用以下 for 循环对列表进行迭代,打印“about-conference”和“conf”
for word in items:
if 'conf' in word:
print word
如何让 if 语句仅在遇到完全匹配时才证明为真,即仅打印“conf”?
谢谢。
【问题讨论】:
考虑以下列表:
items = ['about-conference','conf']
使用以下 for 循环对列表进行迭代,打印“about-conference”和“conf”
for word in items:
if 'conf' in word:
print word
如何让 if 语句仅在遇到完全匹配时才证明为真,即仅打印“conf”?
谢谢。
【问题讨论】:
不要使用in,使用== 来测试是否完全相等:
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'
【讨论】:
试试这个:
for word in list:
if word == 'conf':
print word
【讨论】:
在这个具体示例中,您可以将其重写为:
items = ['about-conference','conf']
if 'conf' in items:
print 'conf'
【讨论】: