How to trim whitespace from a String in Python
Table of Contents
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:
PYTHONstring = " Hello World "
print(string)
BASHHello World
Now let's use the strip()
method to remove the whitespace from the start and end of the string:
PYTHONstring = " Hello World "
stripped = string.strip()
print(stripped)
BASHHello 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.
PYTHONstring = " Hello World "
stripped = string.lstrip()
print(stripped)
BASHHello 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.
PYTHONstring = " Hello World "
stripped = string.rstrip()
print(stripped)
BASHHello 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!
- How to Install Node on Windows, macOS and Linux
- Getting Started with Solid
- Getting Started with Express
- Git Tutorial: Learn how to use Version Control
- How to Serve Static Files with Nginx and Docker
- How to Set Up Cron Jobs in Linux
- Getting Started with Sass
- Learn how to use v-model with a custom Vue component
- Creating a Twitter bot with Node.js
- Building a Real-Time Note-Taking App with Vue and Firebase
- Setting Up Stylus CSS Preprocessor
- Using Axios to Pull Data from a REST API