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))

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))

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))

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

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

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))

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__()

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): = name

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

a = Student("Amit")

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!


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

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


  • JournalDev article on String Length