Table of contents
1.
Introduction
2.
An Introduction to Strings in Python
2.1.
Multiline Strings in Python
3.
Various Approaches for finding String Length in Python 
3.1.
Using len() Function
3.2.
Using a loop
3.3.
Using Join and Count methods
3.4.
Reduce method
3.5.
Sum() and list Comprehension function
4.
Comparison between various Length Function in Python
4.1.
len() function
4.2.
numpy.char.str_len() function
4.3.
str.len() method
5.
Frequently asked questions
5.1.
Can we change the Python string length during runtime?
5.2.
Does the length of a string contain special characters and spaces?
5.3.
What is the Python string length function?
6.
Conclusion
Last Updated: Feb 5, 2025
Easy

Finding String Length in Python

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Do you know how we can find a string's length in python in multiple ways? If not, then don't worry. In this article, we will discuss what exactly len() function is and what are the different methods we can use other than the len() function to calculate the length of the string.

Finding string length in Python

Also see, Merge Sort Python, and Convert String to List Python

An Introduction to Strings in Python

A string refers to a sequence of characters enclosed in double or single quotes.

For example,

NinjaString=” Hello, Ninjas!”
You can also try this code with Online Python Compiler
Run Code

 

In the example above, we assigned “Hello, Ninjas!” to the variable NinjaString. We also could have used single quotes instead of double quotes, which wouldn’t make any difference, but it is advised to be consistent with using any one of them in your use throughout your code.

Click, here to read about Fibonacci Series in Python

Multiline Strings in Python

Multiline strings are created using triple quotes. 

For example,

Code

NinjaString = '''This is a,
multiline string'''
print(NinjaString)
You can also try this code with Online Python Compiler
Run Code


Output

Output

Or

Code

NinjaString = """This is a,
multiline string"""
print(NinjaString)
You can also try this code with Online Python Compiler
Run Code


Output

Output

Various Approaches for finding String Length in Python 

The length of a string refers to the number of characters in a string. There are many ways to access the size of the string in python.

Using len() Function

In python, the len() function is the built-in function for accessing a sequence's length, like a String, ListTuple, or Dictionary.

Syntax of len() function,

len(sequence)
You can also try this code with Online Python Compiler
Run Code


The above syntax sequence refers to the sequence whose length we want to find.

Code

NinjaString = "Hello, Ninjas!"
length = len(NinjaString)
print('length of the string is:',length) 
You can also try this code with Online Python Compiler
Run Code


Output

Output

 

Using a loop

For loop

We can also use for loop for iterating through each character in the string provided and count the number of characters.

For example,

Code

NinjaString = "Hello, Ninjas!"
count = 0
for char in NinjaString:
    count += 1
print("Length of the string is:",count)   
You can also try this code with Online Python Compiler
Run Code


Output

Output

While loop

The while loop can be used for iterating through each character in the string and counting the number of characters.

Code 

NinjaString = "Hello, Ninjas!"
count = 0
while NinjaString[count:]:
    count += 1
print("length of string:",count)  
You can also try this code with Online Python Compiler
Run Code


Output

Output

You can also practice with the help of Online Python Compiler

Using Join and Count methods

We can also use join and count methods for indirectly accessing the length of the string in python.
For example,

Code

NinjaString = "Hello, Ninjas!"
separator = ""
count = NinjaString.count(separator)  # for counting the number of empty substrings
length = count + 1  # adding one to get the length of the string
print("length of the string is:",length)  
You can also try this code with Online Python Compiler
Run Code


Output

Output

In the above example, the separator is set to an empty string to count the number of occurrences of empty substrings in the provided string. The count() method is used for measuring the number of occurrences of the separator in the given string. This will result in the number of characters in the string and add 1 to it. 1 is added to the count as the count() method only counts the number of separators, not the substrings. Therefore, the length is printed using the print function, which is 16 according to the example.


Join() method

The join method is also used for accessing the length of the strings, almost similar to count() method.

For example,

Code

NinjaString = "Hello, World!"
separator = ""
newNinjaString = separator.join(NinjaString)
length = len(newNinjaString)
print("Length is:",length)  
You can also try this code with Online Python Compiler
Run Code


Output

Output

In this example, too, the separator is set to an empty string. The join() method is used for creating a new string (newNinjaString) by joining the character of the original string with the separator.

Join() and Count()

Code 

NinjaString = "Hello, Ninjas!"
length = len("".join(NinjaString.split())) - NinjaString.count(' ')
print("length of the string is :",length)    
You can also try this code with Online Python Compiler
Run Code


Output

Output:

In the example above, NinjaString is set to the string whose length we wish to calculate. The Split() method is used for splitting the strings in words and the join() method joins them into a single string, but no spaces are included in between. The count() method, counts the number of spaces in the string provided and is subtracted from the length of the new string. Hence, we get the final string.Join() and split() methods remove any spaces in the string, and only the characters are counted. Therefore, this method efficiently provides an accurate number of characters in strings.

Reduce method

This method is used for iterating over the string, and a collection element is provided to the reduce function. Iteration is done over the string character by character, and the count is increased to 1 each time. The function reduces () is used from the functools module in Python.

Code

import functools
 
def findLen(NinjaString):
    return functools.reduce(lambda a,b: a+1, NinjaString, 0)
 
NinjaString = 'CodingNinjas'
print("Length of the string is:",findLen(NinjaString))
You can also try this code with Online Python Compiler
Run Code


Output

Output

The reduce function takes three arguments: function, an iterable, and an initial value. The lambda a,b:a+1 adds 1 to the accumulated value ‘a’ for each element in ‘b’ in the given string. The initial value is set to 0. The reduce function is using the lambda function that accumulates the length of the string by adding 1 to the accumulated value for each string element.

Sum() and list Comprehension function

Sum() and list comprehension function can be used to find out the length of a string in the the following way:

Code 

NinjaString = "Hello, Ninjas!"
length = sum(1 for char in NinjaString)
print("Length of the string is:", length)   
You can also try this code with Online Python Compiler
Run Code


Output

Output

In the example above, We have used list comprehension for creating a list of ‘1’ for each character in the string, the sum() function is adding up all ‘1’s in the list to give the length f the string. Therefore we get the final length of the string as 14.

Also see, Swapcase in Python

Comparison between various Length Function in Python

There are multiple ways to find the length of a string. Below is the comparison between them.

len() function

This is an in-built function, which we have also discussed in the above section. The len() function is used for returning the number of characters in the string.

numpy.char.str_len() function

This function is used for finding the length of the string or array of strings.  It gives an array of integers as a result, where each element represents the length of the corresponding string.

Code 

import numpy as np
NinjaString = np.array(['Hello', 'Ninjas!'])
print("Length of words in an array:",np.char.str_len(NinjaString)) 
You can also try this code with Online Python Compiler
Run Code


Output

Output

str.len() method

This is a built-in method in python that can be used to find the length of the string. The function is called on a string object, which returns the number of characters in the string.

Code

NinjaString = "Hello, Ninjas!"
print("Length of the string is",NinjaString.__len__())  
You can also try this code with Online Python Compiler
Run Code


Output

Output

Frequently asked questions

Can we change the Python string length during runtime?

No, the length of the string cannot be changed during runtime. But a new string can be created by modifying the existing string.

Does the length of a string contain special characters and spaces?

Yes, the length of a string contains special characters and spaces.

What is the Python string length function?

The Python string length function returns the number of characters in the string. In python, we can use len() function in order to get the string length.

Conclusion

We hope this article helped you to understand about Python string length. We have discussed what exactly is len() function and the different methods we can use other than the len() function to calculate the length of the string. Refer to our other articles to better understand strings in python.

Check out this article - Quicksort Python

Recommended Readings:

Recommended problems -

You will find straightforward explanations of almost every topic on this platform. You can read more such articles on our platform, Coding Ninjas Studio. So take your learning to the next level using Coding Ninjas. 

Happy Coding!
 

Live masterclass