简体   繁体   中英

How to check if a list contains a string

I need to iterate through a list and check if the value is a string or an int. Is there any easy way to do this in python?

For example:

[1,2,3] would be true.

["a",2,3] would be false.

You could do this using all , which would short circuit once a false condition is met.

>>> my_list = [1, 2, 3]
>>> all(type(d) == int for d in my_list)
True

>>> my_list = ['1', 2, 3]
>>> all(type(d) == int for d in my_list)
False

isinstance could be used when calling all as well:

>>> my_list = [1, 2, 3]
>>> all(isinstance(d, int) for d in my_list)
True

>>> my_list = ['1', 2, 3]
>>> all(isinstance(d, int) for d in my_list)
False

You can use a combination of any() and isinstance() :

In [1]: def contains_string(l):
    ...:     return any(isinstance(item, basestring) for item in l)
    ...: 

In [2]: contains_string([1,2,3])
Out[2]: False

In [3]: contains_string(['a',2,3])
Out[3]: True

basestring handles both "unicode" and "str" string types:

Note that any() would short-circuit as well once it knows the result, see more about that here:

Assuming you meant that you need to check through all the values of the list and that only if they were all integers the function would return True, this is how I'd do it:

def test(list):
    result=True
    for elem in list:
        if type(elem)!=int:
            result=False
    return result

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