1

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']
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131

4 Answers4

5

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']
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Samwise
  • 68,105
  • 3
  • 30
  • 44
3
List = [' a',' b',' c']

print(List) # [' a', ' b', ' c']

List_Trimmed = [*map(lambda x: x.lstrip(), List)]

print(List_Trimmed) # ['a', 'b', 'c']
Luka Samkharadze
  • 111
  • 1
  • 12
3

To remove the leading white spaces, you can use the lstrip function. In your case, for the list:

result = [x.lstrip() for x in List]
print(result)

For removing trailing spaces:

result = [x.rstrip() for x in List]
print(result)

The below code should work in general to remove all white spaces:

result = [x.replace(' ','') for x in List
print(result)
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Nid
  • 31
  • 3
1

You can use strip():

for i in unique_items:
   j = i.strip()
   unique_items_1.append(j)

strip() removes spaces.

You can also use lstrip().

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131