I have a list:
my_list = [\'abc-123\', \'def-456\', \'ghi-789\', \'abc-456\']
and want to search for items that contain the string \'
for item in my_list:
if item.find("abc") != -1:
print item
If you want to get list of data for multiple substrings
you can change it this way
some_list = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
# select element where "abc" or "ghi" is included
find_1 = "abc"
find_2 = "ghi"
result = [element for element in some_list if find_1 in element or find_2 in element]
# Output ['abc-123', 'ghi-789', 'abc-456']
Use filter
to get at the elements that have abc
.
>>> lst = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
>>> print filter(lambda x: 'abc' in x, lst)
['abc-123', 'abc-456']
You can also use a list comprehension.
>>> [x for x in lst if 'abc' in x]
By the way, don't use the word list
as a variable name since it is already used for the list
type.
If you just need to know if 'abc' is in one of the items, this is the shortest way:
if 'abc' in str(my_list):
any('abc' in item for item in mylist)
From my knowledge, a 'for' statement will always consume time.
When the list length is growing up, the execution time will also grow.
I think that, searching a substring in a string with 'is' statement is a bit faster.
In [1]: t = ["abc_%s" % number for number in range(10000)]
In [2]: %timeit any("9999" in string for string in t)
1000 loops, best of 3: 420 µs per loop
In [3]: %timeit "9999" in ",".join(t)
10000 loops, best of 3: 103 µs per loop
But, I agree that the any
statement is more readable.