Find the String length in python with example using len() function

In this tutorial, we will be using python inbuilt function len() in python language. Python len() is used when we want the length of any string. len() function will return the length of the string. String in python is immutable meaning it can't be changed over time.

Python string len() function

Python len() function will return the length. len() function can take parameter as a string, sequence or collection.

Syntax:

len(string)

The above string takes string, sequence or collection as a parameter and returns the length of the same. Below is the example of function len() function

# string.py
str = 'This is test string'
print 'Length of the str is :', len(str)

The above code will output the following length

desert:docs$ python string.py 
Length of the str is : 19

Python string length using for loop and in operator

You can also get the length of the string using for loop with in operator. Below is the example of getting the length of the string

# string.py

def getStringLength(string):
    counter = 0
    for val in string:
        counter += 1
    return counter

beatString = 'this is test beat string'
print 'length of the string using for loop: ', getStringLength(beatString)

The above code will output the following length

desert:docs$ python string.py 
length of the string using for loop:  24