How to trim whitespace from a String in Python

Updated onbyAlan Morel
How to trim whitespace from a String in Python

In Python, strings are just a sequence of characters represented by an array of unicode characters.

Sometimes, we want to trim the whitespace from the start and ends of the string so that it doesn't appear in the output.

In this post, we'll learn how we can strip out the whitespace from the start and end of strings in Python.

Stripping Whitespace from the Start and End

The easiest way to strip whitespace from the start and end of a string is to use the strip() method.

This method comes built-in with Python and is called on a string.

The method will then return that string with the whitespace stripped out.

Let's start with a string:

PYTHON
string = " Hello World " print(string)
BASH
Hello World

Now let's use the strip() method to remove the whitespace from the start and end of the string:

PYTHON
string = " Hello World " stripped = string.strip() print(stripped)
BASH
Hello World

Stripping whitespace from the Start

Sometimes you only want to remove whitespace from the start.

Thankfully, there is a specific method for this, it is called lstrip().

This method will remove whitespace only from the start and leave the rest of the string intact.

PYTHON
string = " Hello World " stripped = string.lstrip() print(stripped)
BASH
Hello World

Stripping whitespace from the End

In other cases, you only want to remove whitespace from the end.

As you might imagine, there is also a specific method for this, it is called rstrip().

This method works like lstrip() but it removes whitespace from the end of the string.

This method will leave alone any whitespace at the start of the string.

PYTHON
string = " Hello World " stripped = string.rstrip() print(stripped)
BASH
Hello World

Conclusion

In this post, we looked at how to strip whitespace from the start and end of a string in Python.

We also learned how to target only the start of the string using the lstrip() method and how to target only the end of the string using the rstrip() method.

Thanks for reading!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.