Boneyflesh
Boneyflesh

Reputation: 353

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

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

How do i do this so that the basis for comparison are the strings inside an array and doesnt act like a wildcard.

Upvotes: 3

Views: 77

Answers (2)

smn14
smn14

Reputation: 21

I used String.split() which splits the string into words.

Upvotes: 0

falsetru
falsetru

Reputation: 369424

Using regular expression with word boundary(\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

Upvotes: 4

Related Questions