Grab The First Word In A List That Is Found In A String. ( Python )
So, I have a list of words like so: activationWords = ['cactus', 'cacti', 'rofl'] And I want to find any of those words and return the first word of any of those words appearing i
Solution 1:
You can use str.find()
here:
>>>activationWords = ['cactus', 'cacti', 'rofl']>>>s = "Wow, rofl I found a cactus in a cacti pile.">>>temp = [(s.find(i), i) for i in activationWords if i in s]>>>print temp
[(20, 'cactus'), (32, 'cacti'), (5, 'rofl')]
>>>printmin(temp)[1]
rofl
str.find()
finds where the string is in the other string. It returns the index of the first letter.
[(s.find(i), i) for i in activationWords]
is a list comprehension that returns a list of tuples, the first item being the result of str.find()
, the second being the word.
Then we use min()
here to get the lowest number, and [1]
to get the word.
Note that you should not name a string str
. It overrides the built-in type.
Post a Comment for "Grab The First Word In A List That Is Found In A String. ( Python )"