The Python Oracle

How do I remove leading whitespace in Python?

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Magic Ocean Looping

--

Chapters
00:00 Question
00:31 Accepted answer (Score 427)
01:09 Answer 2 (Score 117)
01:29 Answer 3 (Score 28)
01:45 Answer 4 (Score 14)
02:27 Thank you

--

Full question
https://stackoverflow.com/questions/9592...

Accepted answer links:
[lstrip()]: http://docs.python.org/library/stdtypes....
[As balpha pointed out in the comments]: https://stackoverflow.com/questions/9592...
[Trimming a string in Python]: https://stackoverflow.com/questions/7618...

Answer 4 links:
[python's standard library textwrap module]: https://docs.python.org/3/library/textwr...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #string #whitespace #trim

#avk47



ACCEPTED ANSWER

Score 445


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:




ANSWER 2

Score 121


The function strip will remove whitespace from the beginning and end of a string.

my_str = "   text "
my_str = my_str.strip()

will set my_str to "text".




ANSWER 3

Score 30


If you want to cut the whitespaces before and behind the word, but keep the middle ones.
You could use:

word = '  Hello World  '
stripped = word.strip()
print(stripped)



ANSWER 4

Score 14


To remove everything before a certain character, use a regular expression:

re.sub(r'^[^a]*', '')

to remove everything up to the first 'a'. [^a] can be replaced with any character class you like, such as word characters.