Skip to content Skip to sidebar Skip to footer

How Can I Find A First Occurrence Of A String From A List In Another String In Python

I have a list of strings (about 100), and I want to find the first occurence of one of them in another string and the index in which it occurred. I keep the index, and afterwords s

Solution 1:

This seems work well and tells you what word it found (although that could be left out):

words = 'a big red dog car woman mountain are the ditch'.split()
sentence = 'her smooth lips reminded me of the front of a big red car lying in the ditch'from sys import maxint
deffind(word, sentence):
    try:
        return sentence.index(word), word
    except ValueError:
        return maxint, Noneprintmin(find(word, sentence) for word in words)

Solution 2:

A one liner with list comprehension would be

return min([indexforindex in [bigString.find(word, startIndex) for word in wordList] ifindex != -1])

But I would argue if you split it into two lines its more readable

indexes = [bigString.find(word, startIndex) for word in wordList]
return min([indexforindex in indexes ifindex != -1])

Solution 3:

import re

deffindFirstOccurence(wordList, bigString, startIndex=0):
    return re.search('|'.join(wordList), bigString[startIndex:]).start()

wordList = ['hello', 'world']
bigString = '1 2 3 world'print findFirstOccurence(wordList, bigString)

Post a Comment for "How Can I Find A First Occurrence Of A String From A List In Another String In Python"