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?
Cheers!
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?
Cheers!
The lstrip()
method will remove leading whitespace on a string:
>>> ' 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:
The function strip
will remove whitespace from the beginning and end of a string.
str = " text "
str = str.strip()
will set str
to "text"
.
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.