str.len() computes the number of characters in each string element, returning an integer Series, with NaN, as a float, for any missing entries, and it's commonly used to filter or flag text that's unexpectedly too short or too long, like validating that a code or ID field always has an exact expected length.
1Understanding Series.str.len()
str.len() computes the number of characters in each string element, returning an integer Series, with NaN, as a float, for any missing entries, and it's commonly used to filter or flag text that's unexpectedly too short or too long, like validating that a code or ID field always has an exact expected length.
Combine str.len() with boolean indexing to quickly find rows where a text field doesn't have its expected fixed length, a common data-validation check.
import pandas as pd
s = pd.Series(["cat", "elephant", "dog"])
print(s.str.len())2Practical Example
Here is a real-world application of Series.str.len() showing how it is used in production Pandas code.
import pandas as pd
df = pd.DataFrame({"code": ["AB123", "CD45", "EF678"]})
invalid = df[df["code"].str.len() != 5]
print(invalid)3Best Practices
Follow these guidelines when working with Series.str.len():
1. Use str.len() combined with boolean indexing to validate that a text field consistently has an expected length, like a fixed-format code or ID
2. Use str.len() instead of applying Python's len() with apply(), for the same vectorized-performance reasons that favor other .str methods over apply()
3. Remember str.len() returns NaN, not 0, for missing values, since there's no string at all to measure the length of
Tip: Combine str.len() with boolean indexing to quickly find rows where a text field doesn't have its expected fixed length, a common data-validation check.
import pandas as pd
s = pd.Series(["cat", "elephant", "dog"])
print(s.str.len())