Hit enter after type your search item

The len() function in Python

Python len() function can be used for getting the length of a given string, sequence and collection. The topic of this tutorial is getting the length of a string, so you can see the examples in the section below. For using len() in sequences and collections, go to list length tutorial.

How to use the len() method for getting string length?

This is how you may use the Python len() method for getting the string length:

Str_len = len(str)

The str is the string which length is returned after using the length method. The len() method returns the string length that is assigned to Str_len variable in above case.

See the demos with code in the next section.

Python string length example

In this example, a string is created and len() function is used to return its length. The returned length is displayed by using the print function:

See online demo and code


Python string length

You can see, the string length is 39.

An example of len() method with for loop

For this example, a list of string items is created. A for loop is used to iterate through the list items. In each iteration, the length of the current item (which is a string) is displayed. Have a look at the code and output:

See online demo and code


string length List

You see, length of each item in the list of strings is returned and displayed.

A demo of getting the string length without using len() method

Well, using the length method for getting the length of the string is the most convenient way and that should be used in your programs. However, as strings are iterable in Python, you may use this to get the length of the string without using the len() method:

See online demo and code


string length without len

Getting the user entered string length

The following small program of Python takes the user input by using the input function. The length of the entered string is displayed by using the len() method as follows:

See online demo and code


string len input

This may be useful where you program requires user input and there is some limitation for entering the number of characters.

This div height required for enabling the sticky sidebar