python - Check if string contains list item -
i have following script check if string contains list item:
word = ['one', 'two', 'three'] string = 'my favorite number two' if any(word_item in string.split() word_item in word): print 'string contains word word list: %s' % (word_item)
this works, i'm trying print list item(s) string contains. doing wrong?
the problem you're using if
statement instead of for
statement, print
runs (at most) once (if @ least 1 word matches), , @ point, any
has run through whole loop.
this easiest way want:
words = ['one', 'two', 'three'] string = 'my favorite number two' word in words: if word in string.split(): print('string contains word word list: %s' % (word))
if want functional reason, this:
for word in filter(string.split().__contains__, words): print('string contains word word list: %s' % (word))
since bound answer performance-related answer though question has nothing performance, more efficient split string once, , depending on how many words want check, converting set
might useful.
regarding question in comments, if want multi-word "words", there 2 easy options: adding whitespace , searching words in full string, or regular expressions word boundaries.
the simplest way add space character before , after text search , search ' ' + word + ' '
:
phrases = ['one', 'two', 'two words'] text = "this has 2 words in it" phrase in phrases: if " %s " % phrase in text: print("text '%s' contains phrase '%s'" % (text, phrase))
for regular expressions, use \b
word boundary:
import re phrase in phrases: if re.search(r"\b%s\b" % re.escape(phrase), text): print("text '%s' contains phrase '%s'" % (text, phrase))
which 1 "nicer" hard say, regular expression less efficient (if matters you).
and if don't care word boundaries, can do:
phrases = ['one', 'two', 'two words'] text = "the word 'tone' matched, 'two words'" phrase in phrases: if phrase in text: print("text '%s' contains phrase '%s'" % (text, phrase))
Comments
Post a Comment