如何检查数组中的任何字符串是否存在于另一个字符串中?
例如:
a = ['a', 'b', 'c']
s = "a123"
if a in s:
print("some of the strings found in s")
else:
print("no strings found in s")
我如何替换如果a在s:行得到适当的结果?
如何检查数组中的任何字符串是否存在于另一个字符串中?
例如:
a = ['a', 'b', 'c']
s = "a123"
if a in s:
print("some of the strings found in s")
else:
print("no strings found in s")
我如何替换如果a在s:行得到适当的结果?
当前回答
为了增加regex的多样性:
import re
if any(re.findall(r'a|b|c', str, re.IGNORECASE)):
print 'possible matches thanks to regex'
else:
print 'no matches'
或者如果你的列表太长- any(re.findall(r'|'.join(a), str, re.IGNORECASE))
其他回答
a = ['a', 'b', 'c']
str = "a123"
a_match = [True for match in a if match in str]
if True in a_match:
print "some of the strings found in str"
else:
print "no strings found in str"
一个惊人的快速方法是使用set:
a = ['a', 'b', 'c']
str = "a123"
if set(a) & set(str):
print("some of the strings found in str")
else:
print("no strings found in str")
如果a不包含任何多字符值(在这种情况下使用上面列出的any),则此方法有效。如果是这样,将a指定为字符串会更简单:a = 'abc'。
为了提高速度,我会使用这样的函数:
def check_string(string, substring_list):
for substring in substring_list:
if substring in string:
return True
return False
只是关于如何在String中获得所有列表元素的更多信息
a = ['a', 'b', 'c']
str = "a123"
list(filter(lambda x: x in str, a))
这是set的另一个解。使用set.intersection。对于一行代码。
subset = {"some" ,"words"}
text = "some words to be searched here"
if len(subset & set(text.split())) == len(subset):
print("All values present in text")
if subset & set(text.split()):
print("Atleast one values present in text")