如果字符串包含在python列表中,请检查该字符串

2024-10-04 07:29:53 发布

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

String = "Alienshave just discovered a way to open cans"
Arr=["Aliens","bird","cactus","John Cena"]

if any(words in String for words in arr):
       print String

此脚本显示Alienshave just discovered a way to open cans

但是我不想它变成printString,因为String中的AlienshaveArr中的Aliens不完全一样

如何做到这一点,以便比较的基础是数组中的字符串,而不是通配符


Tags: toinstringopenjohnwayjustwords
2条回答

我使用String.split()将字符串拆分为单词

使用带单词边界的正则表达式(\b):

Matches the empty string, but only at the beginning or end of a word. A word is defined as a sequence of Unicode alphanumeric or underscore characters, so the end of a word is indicated by whitespace or a non-alphanumeric, non-underscore Unicode character. Note that formally, \b is defined as the boundary between a \w and a \W character (or vice versa), or between \w and the beginning/end of the string. This means that r'\bfoo\b' matches 'foo', 'foo.', '(foo)', 'bar foo baz' but not 'foobar' or 'foo3'.


string = "Alienshave just discovered a way to open cans"
arr = ["Aliens","bird","cactus","John Cena"]

import re
pattern = r'\b({})\b'.format('|'.join(arr)) # => \b(Aliens|bird|cactus|John Cena)\b
if re.search(pattern, string):
    print(string)
# For the given `string`, above `re.search(..)` returns `None` -> no print

相关问题 更多 >