vkumar
vkumar

Reputation: 921

How to check if all items in list are string

If I have a list in python, is there a function to tell me if all the items in the list are strings?

For Example: ["one", "two", 3] would return False, and ["one", "two", "three"] would return True.

Upvotes: 29

Views: 24665

Answers (3)

nathan-hess
nathan-hess

Reputation: 11

Another way to accomplish this is using the map() function:

>>> all(map(lambda x: isinstance(x, str), ['one', 'two', 3]))
False
>>> all(map(lambda x: isinstance(x, str), ['one', 'two', 'three']))
True

Upvotes: 0

Neapolitan
Neapolitan

Reputation: 2153

Answering @TekhenyGhemor's follow-up question: is there a way to check if no numerical strings are in a list. For example: ["one", "two", "3"] would return false

Yes. You can convert the string to a number and make sure that it raises an exception:

def isfloatstr(x):
    try: 
        float(x)
        return True
    except ValueError:
        return False

def valid_list(L):
    return all((isinstance(el, str) and not isfloatstr(el)) for el in L)

Checking:

>>> valid_list(["one", "two", "3"])
False

>>> valid_list(["one", "two", "3a"])
True

>>> valid_list(["one", "two", 0])
False

In [5]: valid_list(["one", "two", "three"]) Out[5]: True

Upvotes: 1

TigerhawkT3
TigerhawkT3

Reputation: 49318

Just use all() and check for types with isinstance().

>>> l = ["one", "two", 3]
>>> all(isinstance(item, str) for item in l)
False
>>> l = ["one", "two", '3']
>>> all(isinstance(item, str) for item in l)
True

Upvotes: 41

Related Questions