The topic of this tutorial is getting the length of a string, so you can see the examples in the section below.
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:
- The str is the string whose length is returned after using the length method.
- The len() method returns the string length that is assigned to Str_len variable in the 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:
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:
Length = 6
in = 2
List = 4
Items = 5
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:
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))
Sample Output:
This may be useful where your program requires user input and there is some limitation for entering the number of characters.