0
0
Pandasdata~5 mins

str.strip() for whitespace in Pandas

Choose your learning style9 modes available
Introduction

We use str.strip() to clean text data by removing extra spaces at the start and end. This helps make data neat and easier to analyze.

When you get data from users and want to remove accidental spaces around names.
When importing text data from files that may have extra spaces.
Before comparing text values to avoid mismatches caused by spaces.
When preparing data for reports or visualizations to look clean.
Syntax
Pandas
Series.str.strip()

This works on pandas Series with text data.

It removes spaces from both start and end of each string.

Examples
Removes spaces from the 'name' column in a DataFrame.
Pandas
df['name'].str.strip()
Removes spaces from the 'city' column strings.
Pandas
df['city'].str.strip()
Sample Program

This code creates a DataFrame with extra spaces in 'name' and 'city'. Then it removes spaces using str.strip() and prints before and after results.

Pandas
import pandas as pd

data = {'name': [' Alice ', ' Bob', 'Charlie ', ' David'],
        'city': [' New York ', 'Los Angeles ', ' Chicago', 'Houston ']}
df = pd.DataFrame(data)

print('Before strip:')
print(df)

# Remove whitespace from both columns

df['name'] = df['name'].str.strip()
df['city'] = df['city'].str.strip()

print('\nAfter strip:')
print(df)
OutputSuccess
Important Notes

str.strip() only removes spaces at the start and end, not inside the text.

If you want to remove spaces inside the text, use other methods like str.replace().

Summary

str.strip() cleans text by removing spaces at start and end.

It helps avoid errors when comparing or analyzing text data.

Use it on pandas Series with string data.