W3docs

How do I trim whitespace?

In Python, you can use the .strip() method to remove leading and trailing whitespace from a string.

In Python, you can use the .strip() method to remove leading and trailing whitespace from a string. Here is an example:

Trim whitespace in Python using strip method

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>

If you want to remove only leading or trailing whitespace, you can use the .lstrip() or .rstrip() methods respectively:

Remove only leading or trailing whitespace in Python

python— editable, runs on the server

You can also pass in specific characters you want to remove

Remove specific characters from the beginning and the end of a string in Python

python— editable, runs on the server