Python Trim: Remove Whitespaces From StringIn this short tutorial, we look at how to use Python to trim a string. We also look at all the built-in methods to remove whitespaces in a string.
If you are here looking for the best solution use this link. However, if you are here to learn, I recommend you follow along with the tutorial.
Table of Contents - Python Trim
- Why do we use Python to trim whitespaces?
- 3 methods to remove whitespaces
- Code and Explanation
- Closing thoughts - Python Trim
- Other Related Concepts
Why do we use Python to trim whitespaces?Python trim essentially means removing whitespaces from a string. While dealing with strings in files or user input strings, whitespaces are a common problem. Since Python considers whitespaces as a character, they would also be printed in case you decide to print the string. In some cases, it could break the logic of your code as well.
So it is best to check for and remove whitespaces in strings and Python comes with 3 inbuilt methods to remove whitespaces.
3 methods to remove whitespaces:Since all the methods have the same syntax I have explained the concepts first and added a code snipped of all the methods in the end.
strip():The strip() method is the most commonly accepted method to remove whitespaces in Python. It is a Python built-in function that trims a string by removing all leading and trailing whitespaces.
strip() syntax is as follows:
Here, “string” refers to the string containing the whitespaces
Parameters:Characters - Optional, a set of characters that you want to remove. if left empty whitespaces would be removed
lstrip():lstrip() in Python is used to trim the string from the left. This means that all whitespaces from the left side of the string will be removed.
The syntax and parameters are the same as strip()
rstrip():rstrip() does the opposite of lstrip(). It removes all the whitespaces from the right side of the string.
The syntax and parameters are again similar to strip()
Code and Explanation:
As you can see we have used strip() first and all the leading and trailing whitespaces were removed.
str_1 = " Hire freelance developers " print(str_1.strip()) #Output = "Hire freelance developers" print(str_1.rstrip()) #Output = " Hire freelance developers" print(str_1.lstrip()) #Output = "Hire freelance developers "
In the following output, the trailing and leading whitespace have been removed as we have used rstrip() and lstrip() respectively.
Closing thoughts - Python TrimLike most others, I would also recommend using strip() as it is hard to judge if the string would contain leading or trailing whitespaces. Hence strip() is the safest bet for performing a Python trim.
However, lstrip() and rstrip() serve very specific use cases and I would recommend practicing them as you might come across a suitable use case.