I have a list of strings in which I want to filter for strings that contains keywords.
I want to do something like:
fruit = re.compile('apple', 'banana', 'peach', 'plum', 'pinepple', 'kiwi']
so I can then use re.search(fruit, list_of_strings) to get only the strings containing fruits, but I’m not sure how to use a list with re.compile. Any suggestions? (I’m not set on using re.compile, but I think regular expressions would be a good way to do this.)
You need to turn your fruit list into the string
apple|banana|peach|plum|pineapple|kiwiso that it is a valid regex. The following should do this for you:As ridgerunner pointed out in comments, you will probably want to add word boundaries to the regex, otherwise the regex will match on words like
plumpsince they have a fruit as a substring.Lastly, if the strings in
fruit_listcould contain special characters, you will probably want to usere.escape.