Pandas
1 min read
Updated 4 Aug 2026
13. String Functions (`.str` accessor)
s = pd.Series([' Alice ', 'BOB', 'charlie99'])
s = pd.Series([' Alice ', 'BOB', 'charlie99'])
s.str.strip() # trim whitespace
s.str.lower() # lowercase
s.str.contains('bob', case=False) # boolean mask
s.str.replace('9', '', regex=True)
s.str.startswith('A')
s.str.endswith('e')
s.str.len()
s.str.split('-') # returns lists
s.str.extract(r'(\d+)') # regex capture group -> DataFrame
s.str.cat(sep=', ') # join
'a,b,c'.split(',') # plain python (for reference)
| Method | Purpose |
|---|---|
contains(pat, regex=) |
substring/regex test |
extract(pat) |
pull out regex groups |
replace(pat, repl, regex=) |
substitute |
split(sep, expand=) |
split into list or columns |
startswith/endswith |
prefix/suffix test |
strip/lstrip/rstrip |
trim |
💡 Tip:
str.split('-', expand=True)splits into multiple columns instead of a column of lists.
⚠️ Common Mistake:
.strmethods return NaN for missing values and skip them — check for NaN before/after.
⭐ Interview Question: How to extract a pattern from text?
df['col'].str.extract(r'(\d{4})')captures the first regex group into a new column.