How do I trim whitespace from a string?

There are a few ways to trim whitespace from a string in Python.

The easiest way is to use the built-in str.strip() method, which removes whitespace characters from the beginning and end of a string. For example:

original_string = "   some text with whitespace   "
stripped_string = original_string.strip()
print(stripped_string)
# Output: "some text with whitespace"

Watch a course Python - The Practical Guide

You can also use the str.lstrip() method to remove whitespace characters from the left side of a string, and str.rstrip() to remove them from the right side. For example:

original_string = "   some text with whitespace   "
left_stripped = original_string.lstrip()
right_stripped = original_string.rstrip()
print(left_stripped)
# Output: "some text with whitespace   "
print(right_stripped)
# Output: "   some text with whitespace"

You can also use replace method, like this:

original_string = "   some text with whitespace   "
stripped_string = original_string.replace(" ","")
print(stripped_string)
# Output: "sometextwithwhitespace"

All the above methods are working on python string and work on python 3.x versions, If you are working on python 2.x then you can use string.strip(), string.lstrip() and string.rstrip() respectively.