Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

# Python Program to Find the Length of String

Last Updated on October 18, 2023 by Ankit Kochar

Strings are a fundamental data type in Python, used to represent text and characters in your code. Manipulating and working with strings is a common task in programming, and one aspect that programmers often need to deal with is determining the length of a string. Whether you’re counting characters, validating input, or formatting output, understanding how to find the length of a string in Python is a crucial skill.

In this article, we’ll explore various methods and techniques to calculate the length of string in Python. We’ll cover both the basic and more advanced approaches, helping you gain a comprehensive understanding of how to work with string length in Python projects.

## What is the Length of the String?

The length of a string can also be defined as the number of elements in the sequence of characters that make up the string. This string can include alphabets, digits, special characters, white spaces, and punctuation marks. Let’s understand the length of the string using a few examples.

Example:

``````st = "PrepBytes"

length = 9``````

In this example, the number of characters present in the string st is 9.

``````st = "PrepBytes@_#"

length = 12``````

In this example, the number of characters present in the string st is 9, including special characters.

``````st = "PrepBytes   "

length = 12``````

In this example, the number of characters present in the string st is 9, including 3 white spaces. Let’s see how to find length of string in Python.

## Python Program to Find the Length of the String

Now, we will see different approaches to finding the python string length.

### Approach 1: String Length in Python Using in-built function len()

In this approach, we have used the in-built python function len() to find the length of the string.

```# Python string program

st = "PrepBytes"
print("Length of string '",st,"' is:", len(st))
```

Output:

``Length of string ' PrepBytes ' is: 9``

### Approach 2: String Length in Python Using for loop and in operator

In this approach, the loop iterates over each character in the string and increments a counter for each character. The value of the counter is returned as a result, which is the length of the string.

```# Python string length

def length_of_string(st):
count = 0
for char in st:
count += 1
return count

st = "PrepBytes"
print("Length of string '",st,"' is:", length_of_string(st))
```

Output:

``Length of string ' PrepBytes ' is: 9``

### Approach 3: String Length in Python Using recursion

In this approach, we will use the recursive function length_of_string, which calls itself until it finds the empty string. After completion of all the function calls in the end we get the length of the string.

```# Python string length

def length_of_string(st):
if st == "":
return 0
else:
return 1 + length_of_string(st[1:])

st = "PrepBytes"
print("Length of string '",st,"' is:", length_of_string(st))
```

Output:

``Length of string ' PrepBytes ' is: 9``

### Approach 4: String Length in Python Using in-built function sum()

In this approach, we have used the in-built python function sum(), which will add 1 as many times as the characters present in the string. In the end, we will get the output sum as the length of the string.

```# Python string length

def length_of_string(st):
return sum(1 for char in st)

st = "PrepBytes"
print("Length of string '",st,"' is:", length_of_string(st))
```

Output:

``Length of string ' PrepBytes ' is: 9``

### Approach 5: String Length in Python Using enumerate function

In this approach, the for loop iterates over the characters in the string using the enumerate() function. The enumerate() function returns a tuple containing the index and value of each character in the string. The length of the string is determined by incrementing the value of length for each iteration of the loop, using index + 1. After all the characters have been processed, the final value of length is returned as the length of the string.

```# Python string length

def length_of_string(st):
length = 0
for index, char in enumerate(st):
length = index + 1
return length

st = "PrepBytes"
print("Length of string '",st,"' is:", length_of_string(st))```

Output:

``Length of string ' PrepBytes ' is: 9``

### Approach 6: String Length in Python Using reduce the () function of functools module

In this approach, the reduce() function from the functools module is used to find the length of the string. The reduce() function applies a function (in this case, a lambda function) to the elements of a sequence (in this case, the string) in a cumulative way, reducing the sequence to a single value. The lambda function takes two arguments, acc and , where acc is the accumulator and is a placeholder for the current character in the string. For each iteration of the reduce() function, the value of acc is incremented by 1. The third argument to reduce() is the initial value of the accumulator, which is set to 0. After all the characters have been processed, the final value of acc is returned as the length of the string.

```# Python string length

from functools import reduce

def length_of_string(st):
return reduce(lambda acc, _: acc + 1, st, 0)

st = "PrepBytes"
print("Length of string '",st,"' is:", length_of_string(st))```

Output:

``Length of string ' PrepBytes ' is: 9``

Conclusion:
In Python, calculating the length of a string is a routine task, but it’s essential for various programming scenarios. Whether you’re performing simple character counts or more complex text processing, having a solid grasp of string length methods is crucial. In this article, we’ve covered several ways to determine the length of string in Python, from the basic len() function to more specialized approaches like using regular expressions and custom counting functions.

As you continue to work with Python, keep these techniques in mind, and choose the one that best fits your specific needs. String length is a fundamental aspect of text manipulation, and mastering it will enhance your ability to work with strings effectively in your Python projects.

## FAQs Related to String Length in Python

Here are some FAQs related to length of string in python.

1. What is the most common way to find the length of a string in Python?
The most common and straightforward method to find the length of a string in Python is by using the built-in len() function. For example, len("Hello, World!") will return 13, as there are 13 characters in the string.

2. Can I use the len() function with other data types besides strings?
Yes, you can use the len() function with sequences like lists, tuples, and even dictionaries (to count the number of keys). It works for any data type that supports a length operation.

3. Are there any performance differences between the various methods for finding string length?
In general, the len() function is the most efficient and recommended way to find the length of a string in Python. Other methods like iterating through the string manually or using regular expressions may be less efficient for large strings, but the difference in performance is usually negligible for most applications.

4. How do I handle Unicode characters when calculating string length?
Python’s len() function counts the number of characters, including Unicode characters, correctly. So, it handles Unicode characters seamlessly, giving you the accurate length of the string.

5. Are there any differences in string length calculation between Python 2 and Python 3?
Yes, there is a difference. In Python 2, len() returns the number of bytes in a string, while in Python 3, it returns the number of characters. This is an important distinction, especially when dealing with Unicode strings, as Python 3 handles them more reliably.