views:

2236

answers:

3

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!

+10  A: 

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:

coobird
Note, though, that lstrip while remove leading *whitespace* which may be more that spaces (tabs etc). That's usually what you want. If you want to remove spaces and spaces only, call " bla".lstrip(" ")
balpha
@balpha: Thanks for point that out! I've added that to the answer.
coobird
A: 

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

str = "   text "
str = str.strip()

will set str to "text".

Marquis Wang
http://docs.python.org/library/string.html#string.strip
Adam Bernier
A: 

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.

Curt Sampson
Casey
True, but he did also (perhaps inadvertantly) ask for the solution for a more general problem, "ie. remove everything before a certain character?", and this is that more general solution.
Curt Sampson