Tums
Tums

Reputation: 589

How to check if the substring exists in a list of values in Python?

I have a list of values which are of different types and I would like to check if a substring exists in the given list and when found, I want to get back the index of it.

I tried doing it with any() but it throws me an error saying in <string>' requires string as left operand, not int. I am assuming, all the values in the list needs to be string in order to use any(). What other way I could use to achieve this?

Here is my Current code:

list_val = [1,18.0, 'printer', 'EXTRACT (123)']
string_val = 'EXTRACT'
any(x in string_val for x in list_val)

I even tried converting all the non-strings into strings and then wanted to use the above any() logic, but that was giving me other errors. I tried the following:

for i, val in enumerate(list_val):
    if not isinstance(val, str):
        list_val[i] = str(val)

This throws me the error: isinstance() arg 2 must be a type or tuple of types

Upvotes: 0

Views: 327

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121486

Just filter your list on strings and only test against those that pass the filter:

any(string_val in item for item in list_val if isinstance(item, str))

Demo:

>>> list_val = [1,18.0, 'printer', 'EXTRACT (123)']
>>> string_val = 'EXTRACT'
>>> any(string_val in item for item in list_val if isinstance(item, str))
True

Note that I used string_val in item, not item in string_val; your example list makes it clear you want to see if there are any elements that contain EXTRACT, not if there are elements that are a substring of EXTRACT (e.g. 'EXT', 'RACT', etc.).

Your second attempt only failed because you appear to have assigned something else to the name str, because the isinstance() call is otherwise correct:

>>> isinstance("foo", str)
True
>>> str = "spam"
>>> isinstance("foo", str)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: isinstance() arg 2 must be a type or tuple of types
>>> del str
>>> isinstance("foo", str)
True

The problem is trivially fixed by removing the str binding again, as I did above You'll have to anyway, as you'll see the same exception using any() with an isinstance() filter.

Not that you need to alter list_val at all for any() to work, however.

Upvotes: 4

Related Questions