I want to find a certain substring inside a string. The string is stored in a list of strings. How can i do it?
+4
A:
So you're searching for all the strings in a list of strings that contain a certain substring? This will do it:
DATA = ['Hello', 'Python', 'World']
SEARCH_STRING = 'n'
print [s for s in DATA if SEARCH_STRING in s]
# Prints ['Python']
Edit at Andrew's suggestion: You should read that list comprehension as "Make a list of all the strings in the list DATA
where SEARCH_STRING
appears somewhere in the string."
RichieHindle
2009-06-12 21:37:07
+1 Very Pythonic! It might be best to explain your example though as a newcomer to Python might not be familiar with list comprehensions.
Andrew Hare
2009-06-12 21:39:54