strip/replace/split
Three everyday cleaning tools: trim whitespace, swap text and break strings into pieces.
In this page:
Syntax
df["column"].str.strip()
df["column"].str.replace("old", "new")
df["column"].str.split(separator)
strip/replace/split
str.strip removes surrounding whitespace, str.replace swaps text (with regex=True for patterns), and str.split breaks strings into lists. Adding expand=True to split spreads the pieces into separate columns.
Note:
Set regex=False in replace for plain text to avoid surprises with special characters.
Example: strip/replace/split
import pandas as pd
df = pd.DataFrame({"full": [" Ada Lovelace ", "Alan Turing"], "phone": ["555-1234", "555-9876"]})
df[["first", "last"]] = df["full"].str.strip().str.split(" ", expand=True)
df["phone"] = df["phone"].str.replace("-", "", regex=False)
print(df)
# Output:
# full phone first last
# 0 Ada Lovelace 5551234 Ada Lovelace
# 1 Alan Turing 5559876 Alan Turing
Related Topics
Common Mistakes
- Forgetting expand=True and getting lists
- Treating . as plain text when regex is on
- Not assigning the cleaned result back
Chapter Summary
- strip trims whitespace
- replace swaps text
- split breaks strings
- expand=True gives columns
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: