Find String Length in Python With Examples


In this tutorial, we are going to discuss how we can find string length in Python. A string’s length or size is mainly required while traversing over it or while performing some operations on it.

So, now let us look at the various methods applying which we can find the length of a given string in Python.

Methods to Find String Length in Python

We can follow any one of the below-given methods to find string length in Python. We are going to discuss each one of them one-by-one.

1. Using the len() method

Looking at the first method, and the easiest one, len() directly returns the length of the passed string object where it is called. The len() method also works on other iterable objects like lists. The below-given code illustrates how we can use the function as well as how it works.


Find String Length in Python

String Length Using len() Method


  • str1 is the given string,
  • Next, we directly call the len() method with the string and print the value returned by it. As we can see, the method gives us the right length for the given string, str1.

2. Defining our Own Function to Find String Length in Python

Now, coming to the next technique, we can define our own function(str_len() in our case) to calculate string length in Python.

Let us see how we can do that:


Find String Length in Python

String Length using User-defined function

In the code above:

  • We define a function str_len() which accepts a string and returns back the length for the same.
  • Inside the function, we initialize a counter, c=0 which practically counts the number of elements in the passed string. We iterate over the string and go on incrementing the counter. Hence, by the end of the for loop, c holds the length of the string. Then, we return c.
  • To check whether our function is working as expected we calculate and print the length of the string, str1. We can see from the output that the function returns a value 9 which is the desired output.


So, in the tutorial, we learned how we can find string length in Python. I hope it helps you understand the topic well. For any questions, feel free to use the comments below.


By admin

Leave a Reply