How to Trim Whitespace in Python?

How do I trim whitespace python?

Is there a Python function that will trim whitespace (spaces and tabs) from a string?

For example, given the input " \t example string\t ", how can I make it become "example string"?

This is a classic one. If you’re looking to trim whitespace in Python, you can use the str.strip() method. It removes spaces, tabs, and any other whitespace characters from both ends of a string. For example:

s = "  \t example string\t  "
s = s.strip()  # This removes leading and trailing whitespace
print(s)  # Outputs: "example string"

Now, if you only want to trim whitespace from one side, you can go with str.rstrip() (for the right side) or str.lstrip() (for the left side). Here’s how:

# Right side only
s = "  \t example string\t  "
s = s.rstrip()  # Removes trailing whitespace
print(s)  # Outputs: "  \t example string"

# Left side only
s = "  \t example string\t  "
s = s.lstrip()  # Removes leading whitespace
print(s)  # Outputs: "example string\t  "

Hope that helps! It’s pretty handy when you want to trim whitespace around the string but leave the content intact.

That’s a great explanation! Just to add to Charity’s point, what if you want to be more specific about which characters to remove? Well, you can pass a custom set of characters to the strip(), rstrip(), or lstrip() functions. For example, you can remove spaces, tabs, and newlines at the same time.

s = " \t\n a string example \t\n "
s = s.strip(' \t\n\r')  # This removes spaces, tabs, newlines, and carriage returns
print(s)  # Outputs: "a string example"

This comes in handy if you have some extra whitespace or hidden characters (like newlines) that you want to clean up without trimming other unintended characters. It’s all about having control over the trimming process when you need it.

Nice additions, Rashmi! Now, if your goal is not just to trim whitespace at the ends but to remove all whitespace (including spaces, tabs, newlines) throughout the entire string, you can use the re.sub() function from Python’s re module. This allows you to replace all whitespace characters with an empty string:

import re

s = "a string  example"
s = re.sub(r'\s+', '', s)  # This removes all whitespace characters, not just at the ends
print(s)  # Outputs: "astringexample"

This method is great when you want to remove all kinds of whitespace throughout the string, not just trimming the ends. You can think of it as a more “global” cleanup for your string when you need to get rid of any extra whitespace.