Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if all items in list are string

Tags:

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.

like image 628
vkumar Avatar asked May 21 '16 00:05

vkumar


People also ask

How do you check if all elements in a list are strings?

To check if all the strings in a List are not empty, call all() builtin function, and pass the list of strings as argument. The following program statement is an example to call all() function with list of strings myList as argument. all() returns True if all the strings in the given list of strings are non-empty.

How do you check all elements in a string Python?

Using Python's "in" operator The simplest and fastest way to check whether a string contains a substring or not in Python is the "in" operator . This operator returns true if the string contains the characters, otherwise, it returns false .

How do you check if all elements in a list are numbers?

The 'all' operator is used to check if every element is a digit or not. This is done using the 'isdigit' method. The result of this operation is assigned to a variable.


1 Answers

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 
like image 102
TigerhawkT3 Avatar answered Sep 30 '22 06:09

TigerhawkT3