Finding a substring within a list in Python

PythonStringList

Python Problem Overview


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.

Python Solutions


Solution 1 - Python

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

Solution 2 - Python

All the answers work but they always traverse the whole list. If I understand your question, you only need the first match. So you don't have to consider the rest of the list if you found your first match:

mylist = ['abc123', 'def456', 'ghi789']
sub = 'abc'
next((s for s in mylist if sub in s), None) # returns 'abc123'

If the match is at the end of the list or for very small lists, it doesn't make a difference, but consider this example:

import timeit

mylist = ['abc123'] + ['xyz123']*1000
sub = 'abc'

timeit.timeit('[s for s in mylist if sub in s]', setup='from __main__ import mylist, sub', number=100000)
# for me 7.949463844299316 with Python 2.7, 8.568840944994008 with Python 3.4
timeit.timeit('next((s for s in mylist if sub in s), None)', setup='from __main__ import mylist, sub', number=100000) 
# for me 0.12696599960327148 with Python 2.7, 0.09955992100003641 with Python 3.4

Solution 3 - Python

Use a simple for loop:

seq = ['abc123', 'def456', 'ghi789']
sub = 'abc'

for text in seq:
    if sub in text:
        print(text)

yields

abc123

Solution 4 - Python

I'd just use a simple regex, you can do something like this

import re
old_list = ['abc123', 'def456', 'ghi789']
new_list = [x for x in old_list if re.search('abc', x)]
for item in new_list:
    print item

Solution 5 - Python

This prints all elements that contain sub:

for s in filter (lambda x: sub in x, list): print (s)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionfrankVView Question on Stackoverflow
Solution 1 - PythonDavid RobinsonView Answer on Stackoverflow
Solution 2 - PythonFrank ZalkowView Answer on Stackoverflow
Solution 3 - PythonunutbuView Answer on Stackoverflow
Solution 4 - PythonoatheadView Answer on Stackoverflow
Solution 5 - PythonHyperboreusView Answer on Stackoverflow