AttributeError: 'str' object has no attribute 'len' (Python)

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

AttributeError: 'str' object has no attribute 'len' (Python) #

The Python "AttributeError: 'str' object has no attribute 'len'" occurs when we access the len attribute on a string. To solve the error, pass the string to the len function to get its length, e.g. len('abc').

attributeerror str object has no attribute len

Here is an example of how the error occurs.

main.py
my_str = 'hello' # ⛔️ AttributeError: 'str' object has no attribute 'len' print(my_str.len)

The error was caused because string objects don't have a len attribute.

To get the string's length, pass it to the len() function.

main.py
my_str = 'hello' result = len(my_str) print(result) # 👉️ 5

The len() function returns the length (the number of items) of an object.

The argument the function takes may be a sequence (a string, tuple, list, range or bytes) or a collection (a dictionary, set, or frozen set).

A good way to start debugging is to print(dir(your_object)) and see what attributes a string has.

Here is an example of what printing the attributes of a string looks like.

main.py
my_string = 'hello world' # [ 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', # 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', # 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', # 'lstrip', 'maketrans', 'partition', 'removeprefix', 'removesuffix', 'replace', 'rfind', 'rindex', # 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', # 'title', 'translate', 'upper', 'zfill'] print(dir(my_string))

If you pass a class to the dir() function, it returns a list of names of the class's attributes, and recursively of the attributes of its bases.

If you try to access any attribute that is not in this list, you would get the "AttributeError: str object has no attribute error".

Since the str object doesn't have a len attribute, the error is caused.

Conclusion #

The Python "AttributeError: 'str' object has no attribute 'len'" occurs when we access the len attribute on a string. To solve the error, pass the string to the len function to get its length, e.g. len('abc').

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.