248

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"
Stevoisiak
  • 23,794
  • 27
  • 122
  • 225
James Wanchai
  • 2,861
  • 4
  • 21
  • 16

7 Answers7

433

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:

Stevoisiak
  • 23,794
  • 27
  • 122
  • 225
coobird
  • 159,216
  • 35
  • 211
  • 226
  • 12
    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 Jun 06 '09 at 08:03
  • 3
    It might be useful to note for new Python programmers that strings in python are immutable, so if you're working with a string 'string_a', you might think string_a.lstrip() will change the string itself, but in fact you'd need to assign the value of string_a.lstrip() to either itself or a new variable, e.g. "string_a = string_a.lstrip()". – Fields Aug 29 '16 at 13:18
  • 2
    note: as there is lstrip() there is also strip() and rstrip() – Alexander Stohr Mar 17 '20 at 15:34
118

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".

jamylak
  • 128,818
  • 30
  • 231
  • 230
Marquis Wang
  • 10,878
  • 5
  • 30
  • 25
28

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)
andreypopp
  • 6,887
  • 5
  • 26
  • 26
Tenzin
  • 2,415
  • 2
  • 23
  • 36
  • 1
    It is worth noting that this _does_ print `'Hello World'` with the middle space intact, for anyone wondering, I guess it has been voted down because the original question was specifically asking to remove _leading_ spaces. – bonapart3 Feb 08 '17 at 15:19
  • 2
    https://docs.python.org/3/whatsnew/3.0.html Print Is A Function The print statement has been replaced with a print() function, with keyword arguments to replace most of the special syntax of the old print statement (PEP 3105). – mbrandeis Sep 04 '17 at 03:58
  • @mbrandeis How is that statement relevant here? – MilkyWay90 Dec 04 '18 at 12:20
16

The question doesn't address multiline strings, but here is how you would strip leading whitespace from a multiline string using python's standard library textwrap module. If we had a string like:

s = """
    line 1 has 4 leading spaces
    line 2 has 4 leading spaces
    line 3 has 4 leading spaces
"""

if we print(s) we would get output like:

>>> print(s)
    this has 4 leading spaces 1
    this has 4 leading spaces 2
    this has 4 leading spaces 3

and if we used textwrap.dedent:

>>> import textwrap
>>> print(textwrap.dedent(s))
this has 4 leading spaces 1
this has 4 leading spaces 2
this has 4 leading spaces 3
Jaymon
  • 5,363
  • 3
  • 34
  • 34
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.

cjs
  • 25,752
  • 9
  • 89
  • 101
  • 4
    I think the guy asked for the "easiest & simplest way" – Nope Jul 26 '09 at 21:20
  • 12
    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. – cjs Aug 05 '09 at 11:20
3

My personal favorite for any string handling is strip, split and join (in that order):

>>> ' '.join("   this is my  badly spaced     string   ! ".strip().split())
'this is my badly spaced string !'

In general it can be good to apply this for all string handling.

This does the following:

  1. First it strips - this removes leading and ending spaces.
  2. Then it splits - it does this on whitespace by default (so it'll even get tabs and newlines). The thing is that this returns a list.
  3. Finally join iterates over the list and joins each with a single space in between.
robmsmt
  • 1,389
  • 11
  • 19
2

Using regular expressions when cleaning the text is the best practice

def removing_leading_whitespaces(text):
     return re.sub(r"^\s+","",text)

Apply the above function

removing_leading_whitespaces("  Example")
"  Example"   -> "Example"

removing_leading_whitespaces("  Example  ")
"  Example  " -> "Example  "

removing_leading_whitespaces("    Example")
"    Example" -> "Example"
Ashok Kumar
  • 411
  • 4
  • 2