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"
To remove everything before a certain character, use a regular expression:
to remove everything up to the first 'a'.
[^a]
can be replaced with any character class you like, such as word characters.If you want to cut the whitespaces before and behind the word, but keep the middle ones.
You could use:
The
lstrip()
method will remove leading whitespaces, newline and tab characters on a string beginning:Edit
As balpha pointed out in the comments, in order to remove only spaces from the beginning of the string,
lstrip(' ')
should be used:Related question:
The function
strip
will remove whitespace from the beginning and end of a string.will set
my_str
to"text"
.