Python trick for finding strings in a list that match a pattern

As part of a project to automate some complicated report generation, I need to interact with a software package that returns all of its output in a series of strings — even “warnings.” The warnings are not special other than that they begin with “Warning:” So, I needed a way to take a list of strings and pull out only the ones that start with “Warning:” After perusing some of the output, I realized it would be sufficient to find strings that contain “Warning.”

I read several suggestions on stack-overflow. Some of them suggested joining the strings into one massive string before searching. This seemed overly complicated. In the end, a list comprehension turned out to be the most satisfying answer (as they so often are). So, from a list of strings called “output,” I can now return only the ones that contain “Warning.”

warnings = [i for i in output if 'Warning' in i]
Previous
Previous

Mlxtend: Making a meta-classifier in a Loop

Next
Next

Pickle a dictionary