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!
- Getting Started with Solid
- Getting Started with Svelte
- Getting Started with Express
- How to Set Up Cron Jobs in Linux
- How to build a Discord bot using TypeScript
- How to deploy a Deno app using Docker
- Getting Started with Deno
- How to deploy a MySQL Server using Docker
- How to deploy a Node app using Docker
- Getting Started with Sass
- Getting User Location using JavaScript's Geolocation API
- Creating a Twitter bot with Node.js