Select Page

How to Solve Python AttributeError: ‘str’ object has no attribute ‘len’

by | Programming, Python, Tips

This error occurs when you try to call the len() method of a string. len() is a built-in Python function, which you can use to get the length of the given object.

You can solve this error by using len(string) instead of string.len().

This tutorial will go through the error and how to solve it with code examples.


AttributeError: ‘str’ object has no attribute ‘len’

AttributeError occurs in a Python program when we try to access an attribute (method or property) that does not exist for a particular object. The len method is a built-in Python method, which means it is always available and does not belong to any particular object. The method returns the length of an object. The syntax of the len() method is:

len(object)

Where object is the object whose length we want to determine. The object can be a sequence, such as a string, bytes, tuple, list or range, or a collection such as a dictionary, set or frozen set.

Example

Consider the following list of object names stored in a CSV file called objects.csv. We want to load this data into a DataFrame, convert the values into a list and then extract the object names of longer than five characters.

car
lorry
brick
surfboard
chassis
skillet
trainer
barbell
pot
sand
import pandas as pd

df = pd.read_csv('objects.csv')

object_names = df.values.flatten().tolist()

object_names_g5 = []

for obj in object_names:
    if obj.len() > 5:
        object_names_g5.append(obj)

print(f'(Object names longer than five letters: {object_names_g5})')

In the above code, we use values to convert the DataFrame to a numpy.ndarray. We then use flatten() to remove the extra dimension, and then tolist() to convert the array to a list.

Once we have the list, we can iterate over the object names using a for loop. We have an if-statement to check how long each object’s name is. If the object name is greater than five, we append that name to a new list called object_names_g5. Let’s run the code to see what happens:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Input In [17], in <cell line: 9>()
      7 object_names_g5 = []
      9 for obj in object_names:
---> 10     if obj.len() > 5:
     11         object_names_g5.append(obj)
     13 print(f'(Object names longer than five letters: {object_names_g5})')

AttributeError: 'str' object has no attribute 'len'

The error occurs because obj is a string and does not have the len() attribute.

Solution

We can solve this error by using the built-in len() method as follows:

import pandas as pd

df = pd.read_csv('objects.csv')

object_names = df.values.flatten().tolist()

object_names_g5 = []

for obj in object_names:
    if len(obj) > 5:
        object_names_g5.append(obj)

print(f'(Object names longer than five letters: {object_names_g5})')

Let’s run the code to see the result:

(Object names longer than five letters: ['surfboard', 'chassis', 'skillet', 'trainer', 'barbell'])

We successfully appended the object names greater than five characters to the new list.

Difference Between len() and .__len__()

The built-in function len() internally calls the magic method __len__() of an object. We can use the len function with any object that has a __len__() method. We can check if an object has a __len__() method by using the dir() function. Let’s look at an example with a string.

string = "Python" 
print(dir(string))
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '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', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

We can see in the list that the method __len__ is there. Let’s call the len() function and the __len__() magic method for this string.

print(len(string))
print(string.__len__())
6
6

Both calls return the same value, which corresponds to the number of characters in the string. Magic methods are special methods that start and end with double underscores and are also known as dunder methods. Normally we do not directly invoke these methods but invoke them internally using functions.

Summary

Congratulations on reading to the end of this tutorial! Remember to use the built-in len() method when you want to get the length of an object.

For further reading on AttributeErrors, go to the articles:

Go to the online courses page on Python to learn more about coding in Python for data science and machine learning.

Have fun and happy researching!