【发布时间】:2018-01-13 20:44:47
【问题描述】:
我试图以某种方式搜索多个字符串并在找到某个字符串时执行某个操作。 是否可以提供字符串列表并通过文件搜索该列表中存在的任何字符串?
list_of_strings_to_search_for = ['string_1', 'string_2', 'string_3']
我目前正在一个接一个地做,在一个新的 if-elif-else 语句中指明我要搜索的每个字符串,如下所示:
with open(logPath) as file:
for line in file:
if 'string_1' in line:
#do_something_1
elif 'string_2' in line:
#do_something_2
elif 'string_3' in line:
#do_something_3
else:
return True
我已经尝试传递列表本身,但是,“if x in line”需要一个字符串,而不是列表。这种事情有什么有价值的解决方案?
谢谢。
【问题讨论】:
-
您是否要匹配单词,例如 "hello" 和 "world" 都在 "hello world" 中找到但未找到 "o",或者会因为您想要找到两次 "o"简单的子串匹配?
-
@JohnZwinck 嘿,约翰,我正在寻找的字符串(例如,string_1)在我的日志文件中是明确的,所以这对我来说并不重要。我将搜索一个只能找到一次的字符串。
标签: python string python-2.7 list search