Feed on
Posts
Comments

assuming you’ve got some string named foo, to remove leading white space:

>>> foo.lstrip()

to remove trailing whitespace:

>>> foo.rstrip()

to remove both lead and trailing whitespace:

>>> foo.strip()


Bookmark and Share

if that was helpful ...

check out the other tips and tricks i've compiled on these pages. you might learn something else interesting!

10 Responses to “remove whitespace in python”

  1. on 10 Sep 2008 at 10:15 am Tod

    Sweet and simple. Thanks

  2. on 13 Jan 2009 at 12:04 pm Daniel

    Nice blog :)

  3. on 31 Mar 2009 at 5:04 pm cprail

    Thank you!

  4. on 29 Oct 2009 at 9:13 pm Luis

    what about removing spaces in the middle of the string?

  5. on 04 Dec 2009 at 8:32 am TJ

    import string # or from string import replace

    yourstring.replace(‘ ‘,”)

  6. on 21 Jan 2011 at 6:48 pm jonathan

    asked google, sent me here, easy answer. ty.

  7. on 07 Nov 2011 at 7:32 pm Nigel

    LOL howdoiremovewhitespace.lstrip()

  8. on 26 Jan 2012 at 2:50 am joe

    Respected sir
    How to remove white spaces which are in middle ?

  9. on 05 Mar 2013 at 5:44 am Virus removal

    and:
    strip(‘\n’)
    to remove “new line” from the end of line

  10. on 06 Oct 2014 at 6:26 am google adwords tool

    google adwords tool

    remove whitespace in python » from the desk of stinkpot

Did I get this wrong? Let me know!

Trackback URI | Comments RSS