Python len() Function

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)
Copy

str: 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)
Copy

Output:

Length of the string: 13
Copy

Common 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.")
Copy

2. 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])
Copy

3. 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

FAQs

What does the len() function do in python

How does the len() function work in python

Latest Posts