How to get string values from list in Python

Published on Aug. 22, 2023, 12:16 p.m.

To get string values from a list in Python, you can use a for loop to iterate through the list and use an if statement to check if the current element is a string. Here’s an example:

my_list = ['hello', 1, 'world', 2, 'python']
string_list = []
for element in my_list:
    if type(element) == str:
        string_list.append(element)
print(string_list)  # Output: ['hello', 'world', 'python']

In this example, we first define a list my_list containing a mix of string and integer elements. We then define an empty list string_list that will store only the string elements. We use a for loop to iterate over the elements of the list. On each iteration, we check if the type of the current element is str (i.e., a string) using the type() function. If it is a string, we append it to the string_list using the append() method. Finally, we print the resulting string_list that contains only the string elements from the original list.

Note that you can modify the if statement to include other types of elements (e.g., int, float, etc.) if needed. Additionally, you can modify the logic inside the loop to perform other operations on the string elements, such as converting them to uppercase, concatenating them, etc.

Tags:

related content