Pandas String Methods
last modified November 17, 2026 Python 3.15
Pandas has a set of tools for cleaning and searching text in a column. They
live behind the .str accessor: you write
series.str.something() to apply a string operation to every
value. This article walks through the methods used most often in practice.
An accessor is a namespace of methods that is only available for a
certain kind of data. The .str accessor is for string Series;
calling it on a column of numbers raises an error. Each method returns a new
Series, leaving the original data untouched unless you assign the result
back.
The str accessor: upper and lower
The methods str.upper() and str.lower() change the
case of every value. This is a common first step when merging data, because
it makes text like names or categories compare consistently.
import pandas as pd s = pd.Series(['Alice', 'BOB', 'charlie']) print(s.str.upper()) print() print(s.str.lower())
The first call converts all three values to capital letters and the second
converts them to small letters. In both cases the result has the same three
row labels as the original Series. On pandas 3.1.1 the resulting data type is
shown as str, the string type used by this version.
$ python str_case.py 0 ALICE 1 BOB 2 CHARLIE dtype: str 0 alice 1 bob 2 charlie dtype: str
Measuring length with str.len
str.len() counts the characters in each value and returns a
Series of integers. It is useful for finding empty entries or unusually long
strings.
import pandas as pd s = pd.Series(['cat', 'elephant', 'dog']) print(s.str.len())
The word elephant has eight characters, so the middle result is
8, while cat and dog each have three. The output is
a Series of whole numbers with the same labels as the input.
$ python str_length.py 0 3 1 8 2 3 dtype: int64
Cleaning whitespace with str.strip
Text copied from files or websites often has stray spaces at the beginning
or end. str.strip() removes that leading and trailing
whitespace, which otherwise prevents values that look identical from
matching.
import pandas as pd s = pd.Series([' Alice ', ' Bob ', 'Charlie ']) print(s.str.strip())
All three names come back without the extra spaces. Notice that
strip only touches the two ends of a value; spaces inside a
value are kept. The printed table still aligns the results by their row
numbers.
$ python str_strip.py 0 Alice 1 Bob 2 Charlie dtype: str
Splitting strings with str.split
str.split() cuts each value into pieces at a separator and
returns a list for every row. With expand=True those pieces are
spread into separate columns instead, which is handy when one column holds
several pieces of information.
import pandas as pd
s = pd.Series(['a,b,c', 'd,e', 'f'])
print(s.str.split(','))
print()
print(s.str.split(',', expand=True))
The first result is a Series whose values are lists such as
[a, b, c]. The second result is a table with three columns
numbered 0, 1 and 2. Rows with fewer pieces get NaN in the
unused columns, because there is no value to put there.
$ python str_split.py 0 [a, b, c] 1 [d, e] 2 [f] dtype: object 0 1 2 0 a b c 1 d e NaN 2 f NaN NaN
Searching with str.contains and startswith
Two methods answer "does this string contain or begin with a given piece of
text?". str.contains searches anywhere in the value and accepts
case=False for a case-insensitive search;
str.startswith only checks the beginning. Both return a boolean
Series that can be used directly as a filter.
import pandas as pd
s = pd.Series(['Alice', 'Bob', 'Charlie', 'Diana'])
print(s.str.contains('a', case=False))
print()
print(s.str.startswith('A'))
With case=False, Alice matches because of its
capital "A", so the first mask marks rows 0, 2 and 3 as True.
The startswith check is case-sensitive by default and only
Alice begins with a capital "A". Such masks are the basis of
boolean indexing.
$ python str_search.py 0 True 1 False 2 True 3 True dtype: bool 0 True 1 False 2 False 3 False dtype: bool
Replacing text with str.replace
str.replace(old, new) swaps one piece of text for another in
every value. It works on literal text by default, so characters that would
have a special meaning in a regular expression are treated as ordinary
characters.
import pandas as pd
s = pd.Series(['a-1', 'b-2', 'c-3'])
print(s.str.replace('-', ':'))
Each hyphen is replaced by a colon, giving values like a:1.
Only the matching part changes; the rest of each string stays exactly as it
was. If you do need regular-expression replacement, pass
regex=True.
$ python str_replace.py 0 a:1 1 b:2 2 c:3 dtype: str
Extracting with str.extract
str.extract uses a regular expression, a pattern that
describes the shape of text, to pull out a piece of each value. Parentheses
in the pattern mark the part to capture. With expand=True the
result is a DataFrame with one column per captured group; with
expand=False and a single group it is a Series.
import pandas as pd s = pd.Series(['Alice 30', 'Bob 25', 'Charlie 41']) print(s.str.extract(r'(\d+)', expand=True)) print() print(s.str.extract(r'(\d+)', expand=False))
The pattern (\d+) captures one or more digits. Here it finds the
numbers at the end of each string. The first call returns a table with a
single column labelled 0; the second returns a plain Series with the same
three numbers. Use the table form when the pattern has several groups.
$ python str_extract.py
0
0 30
1 25
2 41
0 30
1 25
2 41
dtype: str
Missing values and str versus apply
String methods handle missing values automatically: a missing entry stays
missing instead of causing an error. Some methods, such as
contains, accept a na= argument to choose what a
missing entry should report. Calling a Python string method through
apply does not have that protection, because the function is
handed the missing value directly.
import pandas as pd
s = pd.Series(['Alice', None, 'Bob'])
print(s.str.upper())
print()
print(s.str.contains('o', na=False))
print()
try:
s.apply(lambda x: x.upper())
except AttributeError as e:
print(type(e).__name__ + ':', e)
In the first result the missing entry is shown as NaN. In the
second, na=False turns a missing entry into False,
so the mask contains only real booleans. The apply version fails
with an AttributeError because it tries to call
upper() on the missing value. Prefer .str for text
work: it is shorter, safer with missing data, and keeps the same index.
$ python str_missing.py 0 ALICE 1 NaN 2 BOB dtype: str 0 False 1 False 2 True dtype: bool AttributeError: 'float' object has no attribute 'upper'
Source
Pandas Working with Text Data Documentation, Pandas Series.str Documentation, and Pandas str.extract Documentation
In this article we have used the .str accessor to change case,
measure and clean strings, split them, search them, replace parts, extract
matches with a regular expression, and handle missing values. For using
string masks to filter rows see
Pandas boolean indexing, and for
presenting formatted values in a column see
Pandas formatting columns.
Author
List all Pandas tutorials.