James Wanchai James Wanchai - 1 year ago 80
Python Question

Removing starting spaces in Python?

I have a text string that starts with a number of spaces, varying between 2 & 4. What's the easiest & simplest way to remove them ie. remove everything before a certain character?

Answer Source

The lstrip() method will remove leading whitespaces, newline and tab characters on a string beginning:

>>> '     hello world!'.lstrip()
'hello world!'


As balpha pointed out in the comments, in order to remove only spaces from the beginning of the string, lstrip(' ') should be used:

>>> '   hello world with 2 spaces and a tab!'.lstrip(' ')
'\thello world with 2 spaces and a tab!'

Related question:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download