Is there a Python function that will trim whitespace (spaces and tabs) from a string?
So that given input " \t example string\t "
becomes "example string"
.
pythonstringstriptrimwhitespace
Is there a Python function that will trim whitespace (spaces and tabs) from a string?
So that given input " \t example string\t "
becomes "example string"
.
Best Answer
For whitespace on both sides, use
str.strip
:For whitespace on the right side, use
str.rstrip
:For whitespace on the left side, use
str.lstrip
:You can provide an argument to strip arbitrary characters to any of these functions, like this:
This will strip any space,
\t
,\n
, or\r
characters from 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
:That should print out: