简体   繁体   中英

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

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 (eg '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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM