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!
- Create an RSS Reader in Node
- Getting Started with Electron
- Git Tutorial: Learn how to use Version Control
- How to Serve Static Files with Nginx and Docker
- Best Visual Studio Code Extensions for 2022
- How to build a Discord bot using TypeScript
- Getting Started with Deno
- How to deploy a MySQL Server using Docker
- Learn how to use v-model with a custom Vue component
- Learn how to build a Slack Bot using Node.js
- Building a Real-Time Note-Taking App with Vue and Firebase
- How To Create a Modal Popup Box with CSS and JavaScript