Skip to main content
Albero Academy

Text & String Methods

Clean and extract from messy text columns with the vectorised .str accessor and regular expressions.

Chapter 8Pandas15 min readBeginner friendly
  • #Pandas
  • #Text
  • #Regex

Text columns are where the mess lives — stray spaces, inconsistent case, values crammed together. The .str accessor applies Python string methods across a whole column at once, and pairs with regular expressions for serious extraction.

The .str accessor

Prefix any string operation with .str to vectorise it over the column:

vectorised strings
df["name"].str.upper()
df["name"].str.len()
df["email"].str.contains("@example") # boolean mask
df["programme"].str.startswith("Data")
df["city"].str.replace("Bengaluru", "Bangalore")

Cleaning text

The everyday normalisation that fixes most "why don't these match?" bugs:

normalise for matching
df["city"] = (df["city"]
.str.strip() # trim whitespace
.str.lower() # unify case
.str.title()) # Title Case for display
# Chained .str calls read top-to-bottom and stay vectorised.

Splitting & extracting

pull fields out of text
# Split "First Last" into two columns
df[["first", "last"]] = df["name"].str.split(" ", expand=True)
# Take the domain from an email
df["domain"] = df["email"].str.split("@").str[1]
# Get dummy/indicator columns from a multi-value field
df["skills"].str.get_dummies(sep=",")

Regular expressions

For structured text, str.extract with a regex captures groups into columns — the precise tool for parsing codes, ids and patterns:

regex extraction
# Pull the year and a batch letter out of "2026-B batch"
df[["year", "batch"]] = df["cohort"].str.extract(r"(\d{4})-([A-Z])")
df["phone"].str.contains(r"^\+91", regex=True) # starts with +91
df["text"].str.findall(r"#(\w+)") # all hashtags

Practice

On a messy text column: strip and unify case, then filter rows whose value contains a substring. Split a full-name column into first/last. Use str.extract with a regex to pull a year and code out of a combined field.

Key takeaways

  1. 01The .str accessor vectorises Python string methods over an entire column.
  2. 02Normalise with strip/lower/title to fix most text-matching bugs — chain .str calls.
  3. 03str.split(expand=True) splits into columns; .str[i] indexes the pieces.
  4. 04str.extract with a regex captures groups into new columns for structured text.
  5. 05Prefer simple methods; use regex only when needed and comment what it matches.