The .str Accessor
Access string methods on a Series using .str and apply lower(), upper(), strip(), and len() across all values.
The .str Accessor is a free Pandas & NumPy Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Pandas & NumPy Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Introduction to the .str Accessor
Python strings have many useful methods like .lower(), .strip(), and .replace(), but you cannot call them directly on a Pandas Series of strings — you would need a loop. The .str accessor solves this by exposing vectorised versions of Python's built-in string methods on a Series, applying the operation to every element at once without writing a loop and handling NaN gracefully (it returns NaN for missing values).
import pandas as pd
names = pd.Series([' Alice ', 'BOB', ' carol '])
# .strip() removes leading/trailing whitespace from every element
print(names.str.strip())
# 0 Alice
# 1 BOB
# 2 carol
# .lower() lowercases every element
print(names.str.strip().str.lower())
# 0 alice
# 1 bob
# 2 carolCase Conversion Methods
Inconsistent capitalisation is one of the most common data quality issues. The .str accessor provides .lower(), .upper(), .title() (first letter of each word capitalised), and .capitalize() (only first letter of the string). Use .lower() before comparisons and groupby operations to avoid treating 'NYC' and 'nyc' as different groups.
import pandas as pd
df = pd.DataFrame({'city': ['new york', 'LOS ANGELES', 'Chicago', 'HOUSTON']})
df['city_lower'] = df['city'].str.lower()
df['city_title'] = df['city'].str.title()
df['city_upper'] = df['city'].str.upper()
print(df[['city_lower', 'city_title']])
# city_lower city_title
# 0 new york New York
# 1 los angeles Los Angeles
# 2 chicago Chicago
# 3 houston HoustonStripping Whitespace
Leading and trailing whitespace is invisible in displays but causes exact-match comparisons to silently fail. .str.strip() removes whitespace from both ends, .str.lstrip() removes from the left only, and .str.rstrip() removes from the right only. You can also pass a specific character to strip (e.g., .str.strip('$') removes dollar signs).
import pandas as pd
df = pd.DataFrame({'code': [' A001 ', '$B002$', ' C003']})
print(df['code'].str.strip()) # 'A001', '$B002$', 'C003'
print(df['code'].str.strip('$ ')) # 'A001', 'B002', 'C003'Checking Length with .str.len()
.str.len() returns the number of characters in each string element as an integer Series. This is useful for validation — checking that a product code is always 5 characters, that a phone number has the right digit count, or that a text field is not suspiciously short (e.g., a single character suggesting a placeholder).
import pandas as pd
df = pd.DataFrame({'sku': ['A001', 'BB02', 'CCC', 'D0005', 'E1']})
df['sku_len'] = df['sku'].str.len()
print(df)
# Rows with unexpected SKU length
bad_skus = df[df['sku_len'] != 4]
print(bad_skus)
# sku sku_len
# 2 CCC 3
# 3 D0005 5
# 4 E1 2Checking Prefixes and Suffixes
.str.startswith() and .str.endswith() return boolean Series. These are the cleanest way to filter rows based on how a string value begins or ends — for example, selecting all order IDs that start with 'ORD' or all file names that end with '.csv'. They also accept tuples of strings to check multiple prefixes/suffixes at once.
import pandas as pd
df = pd.DataFrame({'file': ['data.csv', 'report.xlsx', 'backup.csv', 'config.json']})
# Filter CSV files
csv_files = df[df['file'].str.endswith('.csv')]
print(csv_files)
# file
# 0 data.csv
# 2 backup.csv
# Multiple suffixes
spreadsheets = df[df['file'].str.endswith(('.csv', '.xlsx'))]
print(spreadsheets.shape) # (3, 1).str.contains() for Substring Search
.str.contains(pattern) returns a boolean Series indicating whether each element contains the given pattern. By default it accepts a regular expression, but you can pass regex=False for a literal substring search. The na=False argument treats NaN as not matching instead of propagating NaN to the result.
import pandas as pd
df = pd.DataFrame({
'description': ['Red apple', 'Green banana', 'Red cherry', None, 'Blue grape']
})
# Find rows containing 'Red' (case-sensitive)
mask = df['description'].str.contains('Red', na=False)
print(df[mask])
# description
# 0 Red apple
# 2 Red cherryNaN Behaviour in .str Methods
When a Series contains NaN values, most .str methods propagate NaN by default — they return NaN for the missing positions in the output Series. Methods that return boolean values (like .str.contains()) default to returning NaN for missing positions, which can cause issues with boolean indexing. Use na=False to treat NaN as non-matching, or na=True to treat it as matching.
import pandas as pd
import numpy as np
s = pd.Series(['hello', None, 'world', np.nan])
# Default: NaN propagates
print(s.str.upper())
# 0 HELLO
# 1 None
# 2 WORLD
# 3 NaN
# contains with na=False: NaN treated as non-matching
print(s.str.contains('o', na=False))
# 0 True
# 1 False
# 2 True
# 3 False.str.count() for Pattern Frequency
.str.count(pattern) counts the number of times a pattern appears in each string element. This is useful for feature engineering in natural language processing — for example, counting how many times a word appears, how many digits a string contains, or how many commas separate values in a delimited field.
import pandas as pd
df = pd.DataFrame({'text': ['hello world', 'foo bar baz', 'a b c d e']})
# Count number of words (spaces + 1)
df['word_count'] = df['text'].str.count(' ') + 1
print(df)
# text word_count
# 0 hello world 2
# 1 foo bar baz 3
# 2 a b c d e 5Chaining .str Methods
Because each .str method returns a new Series, you can chain multiple string operations in one expression. This is the cleanest way to apply several cleaning steps to a text column: strip whitespace, lowercase, and remove special characters — all in a single readable line. The chain evaluates left to right, with each step feeding into the next.
import pandas as pd
df = pd.DataFrame({'tag': [' Python ', ' DATA-SCIENCE ', ' Machine_Learning !']})
df['tag_clean'] = (
df['tag']
.str.strip()
.str.lower()
.str.replace('[-_!]', ' ', regex=True)
.str.strip()
)
print(df)
# tag tag_clean
# 0 Python python
# 1 DATA-SCIENCE data science
# 2 Machine_Learning ! machine learningIndexing Characters with .str[]
The .str[n] notation extracts the character at position n from each string, and .str[start:end] extracts a substring slice. This is vectorised indexing into the strings, useful for extracting fixed-width codes like postal code prefixes, year digits from date strings, or the first letter of a name.
import pandas as pd
df = pd.DataFrame({'code': ['NYC-001', 'LAX-042', 'ORD-018']})
# Extract city code (first 3 chars)
df['city'] = df['code'].str[:3]
# Extract numeric part (chars 4 onwards)
df['num'] = df['code'].str[4:]
print(df)
# code city num
# 0 NYC-001 NYC 001
# 1 LAX-042 LAX 042
# 2 ORD-018 ORD 018Practical Cleaning with .str
Here is a realistic text cleaning pipeline for a product name column that was scraped from a web page. It combines stripping, case normalisation, punctuation removal, and whitespace collapse — a standard pre-processing sequence in any NLP or data cleaning task.
import pandas as pd
df = pd.DataFrame({
'product': [' Apple iPhone 15!!', 'samsung GALAXY s24 ', ' Google Pixel 8 Pro ']
})
df['product_clean'] = (
df['product']
.str.strip()
.str.title()
.str.replace('[^A-Za-z0-9 ]', '', regex=True) # remove punctuation
.str.replace(r'\s+', ' ', regex=True) # collapse extra spaces
.str.strip()
)
print(df['product_clean'].tolist())
# ['Apple Iphone 15', 'Samsung Galaxy S24', 'Google Pixel 8 Pro']Quick Check
Test your understanding of the .str accessor.
Lesson Recap
In this lesson you learned: the .str accessor exposes vectorised string methods on a Pandas Series, including lower/upper/strip for normalisation, startswith/endswith/contains for filtering, and len/count for measurement. Chain multiple .str calls to build readable cleaning pipelines. Use na=False when NaN values are present. Next up we split and replace strings for more advanced transformations.
Frequently asked questions
Is the “The .str Accessor” lesson free?
Yes — the full text of “The .str Accessor” is free to read here on the web, and the Pandas & NumPy Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Pandas & NumPy Academy course, upgrade to CoddyKit PRO.
What will I learn in “The .str Accessor”?
Access string methods on a Series using .str and apply lower(), upper(), strip(), and len() across all values. You practise Pandas & NumPy Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Pandas & NumPy Academy?
No prior experience is required. Pandas & NumPy Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “The .str Accessor” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Pandas & NumPy Academy lesson?
Yes. Every Pandas & NumPy Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.