How do I trim whitespace? How do I trim whitespace? python python

How do I trim whitespace?


For whitespace on both sides use str.strip:

s = "  \t a string example\t  "s = s.strip()

For whitespace on the right side use rstrip:

s = s.rstrip()

For whitespace on the left side lstrip:

s = s.lstrip()

As thedz points out, you can provide an argument to strip arbitrary characters to any of these functions like this:

s = s.strip(' \t\n\r')

This will strip any space, \t, \n, or \r characters from the left-hand side, right-hand side, or both sides of the string.

The examples above only remove strings from the left-hand and right-hand sides of strings. If you want to also remove characters from the middle of a string, try re.sub:

import reprint(re.sub('[\s+]', '', s))

That should print out:

astringexample


Python trim method is called strip:

str.strip() #trimstr.lstrip() #ltrimstr.rstrip() #rtrim


For leading and trailing whitespace:

s = '   foo    \t   'print s.strip() # prints "foo"

Otherwise, a regular expression works:

import repat = re.compile(r'\s+')s = '  \t  foo   \t   bar \t  'print pat.sub('', s) # prints "foobar"