How do I remove leading whitespace in Python?

James Wanchai picture James Wanchai · Jun 6, 2009 · Viewed 337k times · Source

I have a text string that starts with a number of spaces, varying between 2 & 4.

What is the simplest way to remove the leading whitespace? (ie. remove everything before a certain character?)

"  Example"   -> "Example"
"  Example  " -> "Example  "
"    Example" -> "Example"

Answer

coobird picture coobird · Jun 6, 2009

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

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

Edit

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: