HiveBrain v1.2.0
Get Started
← Back to all entries
snippetpythonCriticalCanonical

How to check if a string is a substring of items in a list of strings

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
howchecksubstringstringslistitemsstring

Problem

How do I search for items that contain the string 'abc' in the following list?

xs = ['abc-123', 'def-456', 'ghi-789', 'abc-456']


The following checks if 'abc' is in the list, but does not detect 'abc-123' and 'abc-456':

if 'abc' in xs:

Solution

To check for the presence of 'abc' in any string in the list:

xs = ['abc-123', 'def-456', 'ghi-789', 'abc-456']

if any("abc" in s for s in xs):
    ...


To get all the items containing 'abc':

matching = [s for s in xs if "abc" in s]

Code Snippets

xs = ['abc-123', 'def-456', 'ghi-789', 'abc-456']

if any("abc" in s for s in xs):
    ...
matching = [s for s in xs if "abc" in s]

Context

Stack Overflow Q#4843158, score: 1390

Revisions (0)

No revisions yet.