strip each element in list in python

You can use a loop to iterate through each element in the list and then use the strip() method to remove any leading or trailing spaces. Here's an example:

main.py
my_list = ['  apple  ', '  banana  ', '  orange  ']

for i in range(len(my_list)):
    my_list[i] = my_list[i].strip()

print(my_list)
135 chars
7 lines

Output:

main.py
['apple', 'banana', 'orange']
30 chars
2 lines

Alternatively, you can use a list comprehension to achieve the same result in a more concise way:

main.py
my_list = ['  apple  ', '  banana  ', '  orange  ']

my_list = [element.strip() for element in my_list]

print(my_list)
120 chars
6 lines

Output:

main.py
['apple', 'banana', 'orange']
30 chars
2 lines

related categories

gistlibby LogSnag