The len() method in Python

Python len() method 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() method is used to return its length. The returned length is displayed by using the print function:

#A Demo of String length



str_len = "The example of getting length of string"



print ("string length =", len(str_len))

Output:

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:

#An example of string length with for loop and list



List_string_len = ['String', 'Length', 'in', 'List', 'Items']



for str_len in List_string_len:

    print(str_len, "=", len(str_len))

Output:

string length List

You see, the 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:

#An example of string length with for loop and list

a_str = "The string length without using len() method"

strlen = 0



for c in a_str:

  strlen += 1

print("String length without using len method = ", strlen)

Output:

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:

Python program

#getting length of user entered string



a_string = input('Enter a string? ')



print ("The length of entered string = ", len(a_string))

Output:

string len input

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

Author - Atiq Zia

Atiq is the writer at jquery-az.com, an online tutorial website started in 2014. With a passion for coding and solutions, I navigate through various languages and frameworks. Follow along as we unravel the mysteries of coding together!