Pandas str.strip()

The str.strip() method in Pandas is used to remove leading and trailing whitespace in a Series.

Example

import pandas as pd

# create a Series
data = pd.Series(['  hello  ', ' world ', '   pandas   '])

# remove trailing and leading whitespaces using str.strip() trimmed_data = data.str.strip()
print(trimmed_data) ''' Output 0 hello 1 world 2 pandas dtype: object '''

str.strip() Syntax

The syntax of the str.strip() method in Pandas is:

Series.str.strip(to_strip=None)

str.strip() Argument

The str.strip() method takes the following argument:

  • to_strip (optional) - the string specifying the set of characters to be removed.

str.strip() Return Value

The str.strip() method returns a Series of strings with the specified characters removed from both ends.


Example1: Remove Whitespace Using str.strip()

import pandas as pd

# create a Series with leading and trailing whitespaces
data = pd.Series(['   apple   ', '  banana  ', '   cherry  '])

# remove trailing and leading whitespaces using str.strip() trimmed_data = data.str.strip()
print(trimmed_data)

Output

0     apple
1    banana
2    cherry
dtype: object

Here, data.str.strip() is used in the data Series to remove the leading and trailing whitespaces from the string in the data Series.


Example 2: Remove Specific Characters

import pandas as pd

# create a Series with strings surrounded by asterisks
data = pd.Series(['*hello*', '**world**', '***pandas***'])

# use str.strip to remove asterisks (*) # from the beginning and end of each string trimmed_data = data.str.strip(to_strip='*')
print(trimmed_data)

Output

0     hello
1     world
2    pandas
dtype: object

In the above example, we have used the str.strip(to_strip='*') method to remove asterisks * from the beginning and end of each string in the data Series.

Here, the to_strip argument is set to *, which specifies the character to be removed.

Your builder path starts here. Builders don't just know how to code, they create solutions that matter.

Escape tutorial hell and ship real projects.

Try Programiz PRO
  • Real-World Projects
  • On-Demand Learning
  • AI Mentor
  • Builder Community