Syntax
The len() function in Python is a built-in method used to determine the length of a string or sequence. Its syntax is simple:
len(str)
Copystr
: The string or sequence whose length needs to be determined.
Basic Usage
The primary purpose of the len()
function is to return the number of items in an object. When applied to a string, it provides the length of that string. Here's a basic example:
string_example = "Hello, World!"
length = len(string_example)
print("Length of the string:", length)
CopyOutput:
Length of the string: 13
CopyCommon Use Cases
1. Conditional Checks
The len() function is often used in conditional statements to check if a string is empty:
my_string = "Python"
if len(my_string) > 0:
print("The string is not empty.")
else:
print("The string is empty.")
Copy2. Iterating Through a String
You can use len() in conjunction with a loop to iterate through each character of a string:
text = "Python"
for i in range(len(text)):
print(text[i])
Copy3. Checking String Equality
len() can be used to compare the lengths of two strings:
str1 = "Hello"
str2 = "World"
if len(str1) == len(str2):
print("Both strings have the same length.")
else:
print("The strings have different lengths.")
Copy