For whitespace on both sides use str.strip
:
s = " a string example "
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('
')
This will strip any space,
,
, or
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 re
print(re.sub('[s+]', '', s))
That should print out:
astringexample
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…