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.
解决方案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())