python在多个字符串中查找多个字符串

2024-06-03 03:20:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我可以用这个来判断一组多个字符串中是否有一个存在于另一个字符串中

bar = 'this is a test string'
if any(s in bar for s in ('this', 'test', 'bob')):
    print("found")

但我不知道如何检查一组多个字符串中是否有一个出现在多个字符串中的任何一个。看来这是可行的。从句法上来说,它没有失败,但也不会打印出任何东西:

^{pr2}$

Tags: 字符串intestforstringifisbar
3条回答

需要迭代测试字符串的元组:

a = 'test string'
b = 'I am a cat'
c = 'Washington'
if any(s in test for test in (a,b,c) for s in ('this', 'test', 'cat')):
    print("found")

你可以试试这个:

a = 'test string'
b = 'I am a cat'
c = 'Washington'

l = [a, b, c]

tests = ('this', 'test', 'cat')

if any(any(i in b for b in l) for i in tests):
    print("found")

在这一点上,可能值得编译一个您要查找的子字符串的正则表达式,然后使用它应用一个检查。。。这意味着您只扫描每个字符串一次,而不是潜在地扫描三次(或者您要查找多少个子字符串),并将any检查保持在单一的理解级别。在

import re

has_substring = re.compile('this|test|cat').search
if any(has_substring(text) for text in (a,b,c)):
    # do something

注意:您可以修改表达式以仅搜索整个单词,例如:

^{pr2}$

相关问题 更多 >