Fix Python – Finding a substring within a list in Python [duplicate]

Question

Asked By – frankV

Background:

Example list: mylist = ['abc123', 'def456', 'ghi789']

I want to retrieve an element if there’s a match for a substring, like abc

Code:

sub = 'abc'
print any(sub in mystring for mystring in mylist)

above prints True if any of the elements in the list contain the pattern.

I would like to print the element which matches the substring. So if I’m checking 'abc' I only want to print 'abc123' from list.

Now we will see solution for issue: Finding a substring within a list in Python [duplicate]


Answer

print [s for s in list if sub in s]

If you want them separated by newlines:

print "\n".join(s for s in list if sub in s)

Full example, with case insensitivity:

mylist = ['abc123', 'def456', 'ghi789', 'ABC987', 'aBc654']
sub = 'abc'

print "\n".join(s for s in mylist if sub.lower() in s.lower())

This question is answered By – David Robinson

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0