frankV frankV - 28 days ago 10
Python Question

python: finding substring within a list

This is sort of working, but after hours of frustration and thoroughly searching stack I'm still getting some weird behavior.

Background:

example list:

list = ['abc123', 'def456', 'ghi789']


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


Code:

sub = 'abc'
if any(sub in string for string in list):
print string


and it works, but it prints out every element in the list. Likewise if I try

print any(sub in string for string in list)


it will print
True
for every element in the list.

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

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())