[英]Check a string if it contains a string that's inside a list 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
This script displays Alienshave just discovered a way to open cans
这个脚本显示
Alienshave just discovered a way to open cans
but i dont want it to print
String
since the word Alienshave
in String
is not exactly the same as the word Aliens
found in Arr
但我不希望它
print
String
,因为这个词Alienshave
的String
是不完全一样的字Aliens
中发现的Arr
How do i do this so that the basis for comparison are the strings inside an array and doesnt act like a wildcard. 我如何做到这一点,以便比较的基础是数组中的字符串,并不像通配符那样行事。
Using regular expression with word boundary( \\b
): 使用带有单词边界的正则表达式(
\\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.
单词被定义为Unicode字母数字或下划线字符的序列,因此单词的结尾由空格或非字母数字的非下划线Unicode字符表示。 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.请注意,正式地,
\\b
被定义为\\w
和\\W
字符之间的边界(反之亦然),或者在\\ w和字符串的开头/结尾之间。 This means thatr'\\bfoo\\b'
matches'foo'
,'foo.'
这意味着
r'\\bfoo\\b'
匹配'foo'
,'foo.'
,'(foo)'
,'bar foo baz'
but not'foobar'
or'foo3'
.,
'(foo)'
,'bar foo baz'
但不是'foobar'
或'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
我使用String.split()
将字符串拆分为单词。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.