Skip to content

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 all whitespace characters (including spaces, tabs, and newlines) from the beginning and end of a string. For example:

Trim whitespace from a string in Python

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

<div class="alert alert-info flex not-prose"> Watch a course Python - The Practical Guide</div>

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:

Trim whitespace from the left side of a string in Python

python
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 the str.replace() method, but note that it removes all specified characters rather than just trimming leading and trailing whitespace. For example:

Remove all spaces from a string in Python using the replace method

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

All the above methods work on Python 3 strings.

Dual-run preview — compare with live Symfony routes.