How to get Python String Length? Examples


Python String Length

To find the length of the string, use len() function with this string passed as argument. The len() function returns an integer representing the length of the given string.

https://youtu.be/JhvdSeABNys?si=8Rep6SGee-L4vmNQ

In this tutorial, we will learn how to find the length of a given string, in different scenarios, using example Python programs.

Python String Length

Syntax of len() function

The syntax of len() funtion is

len(mystring)

where mystring is the string whose length has to be found out.


Examples

1. Find length of given string

In this example, we will take a string constant and find its length using len().

Python Program

mystring = 'python examples'

#length of string
length = len(mystring)

print('Length of the string is:', length)

Explanation

  1. The string mystring = 'python examples' is assigned to the variable mystring.
  2. The len() function is called with mystring as its argument to calculate the length of the string. The function returns the total number of characters, including spaces.
  3. The result of the len(mystring) is stored in the variable length, which will be 15 in this case, as there are 15 characters in the string "python examples".
  4. The print() function is used to display the length of the string, which outputs: Length of the string is: 15.

Output

Length of the string is: 15

The number of characters, including all alphabets, spaces, and any characters, is 15 in the given string.


2. Find length of empty string

If you try to find out the length of an empty string, it returns zero.

Python Program

mystring = ''

length = len(mystring)
print('length of the is:', length)

Explanation

  1. The string mystring = '' is an empty string, meaning it contains no characters.
  2. The len() function is called with mystring as its argument to calculate the length of the string. Since the string is empty, the function will return 0.
  3. The result of the len(mystring) is stored in the variable length, which will be 0 in this case.
  4. The print() function is used to display the length of the string, which outputs: length of the is: 0.

Output

length of the is: 0

Summary

In this tutorial of Python Examples, we learned how to find the length of a string with the help of well detailed examples.


Python Libraries