Is there a Python function that will trim whitespace (spaces and tabs) from a string?
Example: \t example string\t
→ example string
Is there a Python function that will trim whitespace (spaces and tabs) from a string?
Example: \t example string\t
→ example string
No one has posted these regex solutions yet.
Matching:
Searching (you have to handle the "only spaces" input case differently):
If you use
re.sub
, you may remove inner whitespace, which could be undesirable.Whitespace on both sides:
Whitespace on the right side:
Whitespace on the left side:
As thedz points out, 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 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
:That should print out: