Last Updated : 15 Oct, 2024
The string len() function returns the length of the string. In this article, we will see how to find the length of a string using the string len() method.
Example:
Python
s1 = "abcd"
print(len(s1))
s2 = ""
print(len(s2))
s3 = "a"
print(len(s3))
String len() Syntax
Parameterlen(string)
String: string of which you want to find the length.
Return:It returns an integer which is the length of the string.
More Examples of String len() FunctionThe len() method is used to find the length of an object in Python. By using len(), we can find the length of strings and lists. In this example, we are finding the length of a string.
Example 1: Len() function with tuples and stringIn this example, we are counting the length of the tuples and list.
Python
# Python program to demonstrate the use of
# len() method
# with tuple
tup = (1,2,3)
print(len(tup))
# with list
l = [1,2,3,4]
print(len(l))
Example 2: Python len() TypeError
In this example, we are using len() with a boolean value and find TypeError as a result.
Python
Output
TypeError: object of type 'bool' has no len()Example 3: Python len() with dictionaries and sets
In this example, we are using Python len() with dictionaries and sets to find the length of dictionary and set.
Python
# Python program to demonstrate the use of
# len() method
dic = {'a':1, 'b': 2}
print(len(dic))
s = { 1, 2, 3, 4}
print(len(s))
Example 4: Python len() with custom objects
In this example, we are using len() to find the length of custom objects and to find the length of an object in Python.
Python
class Public:
def __init__(self, number):
self.number = number
def __len__(self):
return self.number
obj = Public(12)
print(len(obj))
Example 5: Python len() with range()
In this example, we are using the len() function to find the length of the range() function.
Python
l=range(1,10)
print(len(l))
In this article, we have covered about Python string len() function and discussed its working. len() function is used to find the length of a string. It is a very common yet important function of string methods.
Also Read:Read More String Methods
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4