Find String Length in Python

We can find string length in Python using the built-in len() function. Let’s look at how this function works, and also let’s try finding the length of various types of Python strings using len().


Using len()

Let’s look at some simple examples to illustrate len().

>>> a = "Hello from AskPython"
>>> print(len(a))
20

This prints 20 because it is the number of characters in the string. We can thus find the length using len().

Even when the string has special characters, as long as it can be encoded in some Unicode format, we can calculate it’s length.

>>> a = 'AåBç'
>>> print(len(a))
4

For strings with special escape characters (they are prefixed by a backslash(\), only the character is counted towards the length and not the backslash. Examples include (\n, \t, \', etc)

>>> a = 'A\t\t'
>>> print(len(a))
3

>>> b = 'A\n\nB'
>>> print(len(b))
4

>>> c = 'A\'B'
>>> print(len(c))
3

For raw strings, since they treat backslash (\) as literal, the backslash will be counted towards the length of the string.

>>> s = r'A\t\t'
>>> print(len(s))
5

Working of len()

When we call the len() function using the String object, the __len__() method of the String object is called.

>> a = "Hello from AskPython"
>>> a.__len__()
20

To prove this, let us implement our own len() on a custom Class. Since __len__() works on objects, we must inherit the class object.

class Student(object):
    def __init__(self, name):
        self.name = name

    def __len__(self):
        print("Invoking the __len__() method on the Student Object to find len()...")
        count = 0
        for i in self.name:
            count += 1
        return count


a = Student("Amit")
print(len(a))

Since the len() method invokes __len__(), we will go through the function, which counts the number of objects in the iterable. Since we pass a string, we will simply get the length, which will come out to be 4!

Output

Invoking the __len__() method on the Student Object to find len()...
4

We have thus implemented our own len() method for the class Student! Amazing, isn’t it?


References

  • JournalDev article on String Length