How to Get Only String from a List in Python?

By Hardik Savani October 30, 2023 Category : Python

Hi,

In this definitive guide, we will show you get string only values from a list in python. let us discuss about python get only string from list. I would like to share with you how to get only string value from list in python. let us discuss about how to get only string from a list in python.

If you have list in python with string and non-string values in list and you want to get only string values from list in python, then there are several ways to do that. i will give you simple two examples here using comprehension with isinstance() and isdigit() functions. so, let's see the following examples:

You can use these examples with python3 (Python 3) version.

let's see below a simple example with output:

Example 1:

main.py

# Create New List with Item
myList = ["a", 1, 2, "b", "c", 4, 5, "d"]
    
# Get string only values from a list in Python
newList = [val for val in myList if isinstance(val, str)]
    
print(newList)

Output:

['a', 'b', 'c', 'd']

Example 2:

main.py

# Create New List with Item
myList = ["a", "1", "2", "b", "c", "4", "5", "d"]
  
# Get string only values from a list in Python
newList = [val for val in myList if not val.isdigit()]
  
print(newList)

Output:

['a', 'b', 'c', 'd']

I hope it can help you...

Tags :
Shares