Online Tutorials & Training Materials | STechies.com
Register Login

Python String Length | len() Method with Example

21 Dec 2018 6:47 am || 0

What is len() function in Python

Python len() function is used to calculate the length of the list in Python. It is an inbuilt function in python that returns the length (number of characters) of string in Python.

Parameter of len() Function 

len() function takes string or list of elements as a parameter

Syntax of len() Function

len(string)

Return Value of len() Function Python

The output prints the length of the string or number of elements present in the list.

Note: If an invalid argument is passed then a TypeError Exception will be raised

An example of the same would be-

Code to find the length of a string in Python

Please follow the example below to get the length of the string using len().

stringlenth = 'Stechies'
print("String Length: ",len(stringlenth))

Output

String Length: 8

Find the number of elements in a list in Python

#!/usr/bin/python
listB, listD = [9977, 'xyz', 'sahara', 'stechies'], [459, 'pqr', 234]
print("Length of list B : ", len(listB))
print("Length of list D : ", len(listD))

Output

Length of list B :  4
Length of list D :  3

Calculate the length of a string without using len() function in Python

However, if you are interested in finding the length of a string without using len() function, you can follow this example instead.

def string_length(s):   
    if s == '': return 0
    return 1 + string_length(s[1:])
len = string_length("Enter String :")
print("The length is :", len)

Output

('The length is :', 14)