0
0
Pandasdata~5 mins

str.len() for string length in Pandas

Choose your learning style9 modes available
Introduction

We use str.len() to find out how many characters are in each text entry in a list or column. It helps us understand the size of text data easily.

Checking the length of names in a customer list to find very short or very long names.
Measuring the length of product descriptions to filter out too short or too long texts.
Analyzing tweets or messages to see how many characters each contains.
Preparing text data for models that need inputs of certain length.
Syntax
Pandas
Series.str.len()

This works on a pandas Series that contains text data.

It returns a new Series with the length of each string.

Examples
Finds the length of each fruit name in the Series.
Pandas
import pandas as pd
s = pd.Series(['apple', 'banana', 'cherry'])
lengths = s.str.len()
print(lengths)
Handles empty strings and missing values (None) safely.
Pandas
import pandas as pd
s = pd.Series(['cat', '', None, 'elephant'])
lengths = s.str.len()
print(lengths)
Sample Program

This program creates a list of fruit names and then finds how many letters each name has using str.len(). It prints both the original names and their lengths.

Pandas
import pandas as pd

# Create a Series with some text data
fruits = pd.Series(['apple', 'banana', 'cherry', 'date', 'fig', 'grape'])

# Use str.len() to get the length of each fruit name
lengths = fruits.str.len()

# Print the original Series and the lengths
print('Fruits:')
print(fruits)
print('\nLengths of each fruit name:')
print(lengths)
OutputSuccess
Important Notes

If the Series has missing values (NaN), str.len() returns NaN for those entries.

This method counts all characters including spaces and punctuation.

Summary

str.len() helps count characters in each string of a pandas Series.

It is useful for quick checks on text data size.

Handles empty and missing values gracefully.