How do I trim whitespace?

ghz 3months ago ⋅ 36 views

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".

Answers

Yes, Python provides the str.strip() method, which removes leading and trailing whitespace (including spaces, tabs, and newline characters) from a string.

Here’s how you can use it:

s = "  \t example string\t  "
trimmed = s.strip()
print(trimmed)  # Output: "example string"
  • str.strip() removes both leading and trailing whitespace.
  • If you only want to remove leading whitespace, you can use str.lstrip().
  • If you only want to remove trailing whitespace, you can use str.rstrip().

Example:

s = "  \t example string\t  "
print(s.strip())    # "example string"
print(s.lstrip())   # "example string\t  "
print(s.rstrip())   # "  \t example string"