我正尝试搜索多个字符串,并在找到某个特定字符串时执行某个操作。 是否可以提供一个字符串列表并遍历文件以搜索列表中存在的任何字符串?
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”需要一个单独的字符串而不是一个列表。针对这种情况有什么好的解决方案呢?
谢谢。