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.
In this tutorial, we will learn how to find the length of a given string, in different scenarios, using example Python programs.
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
- The string
mystring = 'python examples'
is assigned to the variablemystring
. - The
len()
function is called withmystring
as its argument to calculate the length of the string. The function returns the total number of characters, including spaces. - The result of the
len(mystring)
is stored in the variablelength
, which will be15
in this case, as there are 15 characters in the string "python examples". - 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
- The string
mystring = ''
is an empty string, meaning it contains no characters. - The
len()
function is called withmystring
as its argument to calculate the length of the string. Since the string is empty, the function will return0
. - The result of the
len(mystring)
is stored in the variablelength
, which will be0
in this case. - 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.