Search code examples
pythonfor-looparraylistremoving-whitespace

Remove white spaces from the beginning of each string in a list


How do I remove the spaces at the beginning of each string in a list?

List = [' a', ' b', ' c']

Here is what I tried, but the list remained the same:

unique_items_1 = []

for i in unique_items:
    j = i.replace('^ +', '')
    unique_items_1.append(j)

print(List)

My expected result was:

List = ['a', 'b', 'c']

Solution

  • Use str.lstrip in a list comprehension:

    my_list = [' a', ' b', ' c']
    
    my_list = [i.lstrip() for i in my_list]
    print(my_list)  # ['a', 'b', 'c']