W3docs

How do I trim whitespace from a string?

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

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— editable, runs on the server

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> 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— editable, runs on the server

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— editable, runs on the server

All the above methods work on Python 3 strings.