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


Borislav Hadzhiev

Wed Apr 20 20222 min read


Photo by Sam Chang

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.
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.
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.
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 classes' 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.

Use the search field on my Home Page to filter through my more than 1,000 articles.