Tom
Tom

Reputation: 215

Removing leading whitespace from a string

Hi I have list of strings in python

[" 0", " 1", " 2"] 

and I want to remove the whitespace from the start of one of them.

How would I do this?

Upvotes: 2

Views: 5202

Answers (5)

Anuj
Anuj

Reputation: 9622

If you want the the result to be a list of intergers then try this

>>> w = [" 0", " 1" ," 2"]
>>> map(lambda a:eval(a),w)
[0, 1, 2]

else if you want it to be a list of string

>>> w = [" 0", " 1" ," 2"]
>>> map(lambda a:a.strip(),w)
['0', '1', '2']
>>>

Upvotes: -1

eyquem
eyquem

Reputation: 27565

boooooh...

li = [" 0", " 1", " 2"]
li = map(str.lstrip,li)

Upvotes: 2

Sven Marnach
Sven Marnach

Reputation: 601351

If you want to remove the whitespace from all of them, you could use

a = [" 0", " 1", " 2"]
b = [s.lstrip() for s in a]

If you really only want to strip one of them, use

a[i] = a[i].lstrip()

where i is the index of the one you want to strip.

Upvotes: 6

kurumi
kurumi

Reputation: 25599

you can use lstrip() if you want to remove from start. Otherwise, you can use strip() to remove trailing and leading.

Upvotes: 1

Santiago Alessandri
Santiago Alessandri

Reputation: 6855

To remove the spaces you can use the strip method, then use the positional operator to access and assign that position on the list, for the element in position 0 you should do:

l[0] = l[0].strip()

Upvotes: 2

Related Questions