Strip methods

Strip from both ends

Use .strip.

str.strip([chars])
  • chars - Optional. The set of characters to be removed (order is ignored). If omitted or None, the argument defaults to removing whitespace.

Strip from one side

Use .lstring for left and .rstrip for right.

' abc '.lstrip()
# 'abc '
' abc '.rstrip()
# ' abc'

You can pass a character set too:

' abc '.rstrip('bc ')
# ' a'

Remove whitespace

The default.

Remove any whitespace (space, tab, newline) from the ends.

value.strip()

e.g.

' abc def '.strip()
# 'abc def'
'\tabc\tdef\n'.strip()
'abc\tdef'

Remove chosen character

'-abc-def-'.strip('-')
# 'abc-def'

Note that any if there are other characters on the ends, including whitespace, nothing will be stripped there.

'-abc-def- '.strip('-') 
'abc-def- '

See below for handling tht.

Remove multiple characters

Here we specify a dash and a space get removed.

' -abc-def- '.strip('- ')

Here, we specify #, $, and c will get removed.

'$#%abc'.strip('#$c')
'%ab'