← Back to Pandas Course | Chapter 5: Data Cleaning | Lesson 5 of 7

strip/replace/split

Three everyday cleaning tools: trim whitespace, swap text and break strings into pieces.

In this page:

  1. strip/replace/split
Syntax
python
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

python
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
  1. Forgetting expand=True and getting lists
  2. Treating . as plain text when regex is on
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.