Pandas Series.str.strip() Function

Pandas 常用函数Pandas Common Functions


Series.str.strip()It is a function in Pandas used to remove whitespace characters from both ends of strings.

During data processing, we often need to clean text data from user input or read from files, which may contain extra spaces, tabs, or newlines at both ends.strip()The function can remove whitespace characters from both ends of strings, making the data cleaner and more organized.

Word Definition:stripIt means "to peel off, remove", and here it indicates removing whitespace characters from both ends of strings.


Basic Syntax and Parameters

str.strip()It is the string accessor method of Series, so you need to first have a Series containing strings, and then use the.straccessor to call it.

Syntax Format

Series.str.strip(to_strip=None)

Parameter Description

Parameter Type Required? Description Default Value
to_strip str Optional Specify the set of characters to be removed. If not specified, whitespace characters (including spaces, tabs, newlines, etc.) are removed by default. None (whitespace characters)

Function Description

  • Return ValueReturns a new Series with whitespace characters removed from both ends.
  • EffectRemoves whitespace characters at both ends of each string element, while whitespace characters in the middle remain unchanged.
  • NoteOnly removes characters at both ends of the string; characters in the middle are not affected.

Examples

Through a series of examples from simple to complex, let us thoroughly masterstr.strip()its usage.

Example 1: Basic Usage - Removing Leading and Trailing Whitespace

Example

import pandas as pd

# Create a Series containing whitespace characters
s = pd.Series(['  hello  ', 'tworldt', 'nexamplen', '  python  '])

# Use str.strip() to remove whitespace from both ends
result = s.str.strip()

print("Original Series:")
print(repr(s))  # Use repr() to display raw characters (including invisible characters)
print(Result after removing whitespace from n:)
print(result)

Output result:

原始 Series:
0     '  hello  '
1     'tworldt'
2      'nexamplen'
3     '  python  '
dtype: object

去除空白后的结果:
0    hello
1    world
2    example
3    python

Code explanation:

  1. pd.Series([' hello ', ...])Created a Series containing whitespace characters.
  2. repr(s)Used to display the original content of the string, including invisible characters such as spaces and tabs.
  3. s.str.strip()Removed whitespace characters from both ends of each string.
  4. Whitespace characters in the middle of the string remain unchanged.

Example 2: Removing Specified Characters

You canto_stripspecify the characters to be removed via the parameter.

Example

import pandas as pd

# Create a Series containing specific characters
s = pd.Series(['xxxhello xxx', 'yyyworldyyy', 'zzzexamplezzz'])

# Strip 'x' characters from both ends
result_x = s.str.strip('x')
# Strip 'y' characters from both ends
result_y = s.str.strip('y')
# Strip 'z' characters from both ends
result_z = s.str.strip('z')

print("Original Series:")
print(s)
print("nResult after removing 'x':")
print(result_x)
print("nResult after removing 'y':")
print(result_y)
print("nResult after removing 'z':")
print(result_z)

Output result:

原始 Series:
0    xxxhello xxx
1    yyyworldyyy
2    zzzexamplezzz
dtype: object

去除 'x' 后的结果:
0    hello xxx
1    yyyworldyyy
2    zzzexamplezzz

去除 'y' 后的结果:
0    xxxhello xxx
1    worldyyy
2    zzzexamplezzz

去除 'z' 后的结果:
0    xxxhello xxx
1    yyyworldyyy
2    examplezzz

Code explanation:

  • strip('x')Only the 'x' characters at both ends of the string are removed.
  • If there are the same characters in the middle of the string, they will not be removed.
  • Only characters that appear consecutively at both ends are removed.

Example 3: Handling Whitespace Issues in Real Data

When processing data from files or user input,strip()this function is very useful.

Example

import pandas as pd

# Simulate username data collected from a form (may contain extra spaces)
usernames = pd.Series(['  admin  ', 'user123', '  moderator  ', 'guest'])

# cleanupUsername
cleaned_usernames = usernames.str.strip()

print(Original username:)
print(usernames)
print(nCleaned username:)
print(cleaned_usernames)

# Remove whitespace before comparing
print(n Whether they are equal after removing whitespace:)
print(cleaned_usernames == 'admin')

Output result:

原始用户名:
0       admin
1      user123
2    moderator
3        guest
dtype: object

清理后的用户名:
0       admin
1      user123
2    moderator
3       guest

清理后的用户名:
0     True
1    False
2    False
3    False

Code explanation:

  • strip()Removed spaces before and after the usernames.
  • This ensures that the user-entered' admin 'can be matched correctly.'admin'。
  • This is an important step in data cleaning, which can avoid matching failures caused by spaces.

Related Functions

Pandas also provides other functions for removing whitespace:

  • str.lstrip()- Removes whitespace only from the left side (beginning) of the string.
  • str.rstrip()- Removes whitespace only from the right side (end) of the string.

Example

import pandas as pd

s = pd.Series(['  hello world  '])

print(Original string:, repr(s[0]))
print("strip():", repr(s.str.strip()[0]))       # Remove both ends
print("lstrip():", repr(s.str.lstrip()[0]))     # Remove left
print("rstrip():", repr(s.str.rstrip()[0]))     # Remove right

Output result:

原始字符串: '  hello world  '
strip(): 'hello world'
lstrip(): 'hello world  '
rstrip(): '  hello world'

Notes

  • str.strip()By default, whitespace characters are removed, including spaces, tabs (\t), newlines (\n), carriage returns (\r), etc.
  • This function only removes characters at both ends of the string; characters in the middle are not affected.
  • If the Series contains NaN values,strip()it will return NaN.
  • This function returns a new Series and does not modify the original data.

Pandas 常用函数Pandas Common Functions

Other Extensions