In this post, you’ll learn the different ways to trim a string in Python, using the .strip(), .lstrip(), and .rstrip() methods.
.strip()
removes any trailing and leading whitespaces, including tabs,- .
lstrip()
removes any leading whitespace – meaning the left-side of the string, .rstrip()
removes any trailing whitespace- meaning, the right-side of the string.
All these methods work on spaces as well as \n
, \r
, \t
, \f
, meaning you can trim new lines, tabs and much more.
Check out some other Python tutorials on datagy, including our complete guide to styling Pandas and our comprehensive overview of Pivot Tables in Pandas!
Using .strip to trim a string in Python
The .strip() method can be used to trim whitespace on both ends of a string.
Let’s take a look at a quick example:
messy_string = ' apples '
cleaned_string = messy_string.strip()
print(cleaned_string)
# Returns
# apples
Using pd.str.strip() to trim strings in Pandas
There may be times when you need to trim strings in Pandas. For example, if you are importing web-scraped data, you may end up with very messy strings.
Let’s take a look at how to trim strings in Pandas with an example:
import pandas as pd
df = pd.DataFrame({'a':[' aaa ', 'b '], 'b':[1,2]})
print(df.head())
# Returns
# a b
# 0 aaa 1
# 1 b 2
Now, let’s format the ‘a’ column with the strip() method:
df['a'] = df['a'].str.strip()
print(df.head())
# Returns
# a b
# 0 aaa 1
# 1 b 2
Now you know how to strip whitespace from a Pandas dataframe!
Using .rstrip() to strip trailing spaces in Python
To trim any trailing whitespace (the space to the right of a string), you can use the .rstrip(). This works like the .strip() method in that you place it following a string.
Let’s take a look at another example:
messy_string = ' apples '
cleaned_string = messy_string.rstrip()
print(cleaned_string)
# Returns
# apples
Using .lstrip() to strip leading spaces in Python
To trim any leading whitespace (the space to the left of a string), you can use the .lstrip(). This works like the .strip() method in that you place it following a string.
Let’s take a look at another example:
messy_string = ' apples '
cleaned_string = messy_string.lstrip()
print(cleaned_string)
# Returns
# apples
Conclusion
In this post, you learned how to use the .strip(), .rstrip(), and .lstrip() methods to generate new strings, that have their whitespace removed. The .strip() method removes whitespace from beginning and end. The .rstrip() method strips trailing whitespace, and the .lstrip() method removes whitespace from the beginning of a string.
To learn more about the strip method, check out the official documentation.
Pingback: Python: Remove Newline Character from String • datagy
Pingback: Data Cleaning and Preparation in Pandas and Python • datagy