How to get the length of a string in Python?

Problem

To calculate and print the length of a provided string of characters / words using Python 3.

Solution

There are many simple ways to find the length of a string in Python. We will discuss some of those techniques in this short tutorial, alongside with the required Python 3 code.

Using len() function:

The len() function calculates and returns the length of a given string. It considers white spaces in the calculation.

Code:

mystring = 'Calculate the length of this string'
print("String:", mystring)
print("String length:",len(mystring))

Output:

String: Calculate the length of this string
String length: 31

Using For loop:

Initially, we assign an integer with a value of 0. Then by using For loop, we will loop through each element in the string. For each iteration, the count value is increased by 1. Hence, by the end of the loop, we would have the length of the string.

Code:

def getlength(value):
    count=0
    for i in value:
        count+=1
    return count
mystring = "My name is John"
print("String:", mystring)
print("String length:",len(mystring))

Output:

String: My name is John
String length: 15

Using join() and count() function:

In this technique, we would initialize a sample string. Using the join() function, we would concatenate each character of the provided string value with the sample string. Using count(sample_string)+1, we would count the concatenated sample string with the addition of 1. Thus we obtain the length of the provided string.

Code:

def getlength(value):
    sample_string = 'ab'
    return sample_string.join(value).count(sample_string)+1
mystring = 'Calculate my length'
print("String:", mystring)
print("String length:",getlength(mystring))

Output:

String: Calculate my length
String length: 19

Bonus:

  • sample_string.join(value) – Will provide with output like the screenshot below.