How to find the length of a string in python

How to find the length of a string in python :

We need to find the length of a string most of the time while development of any software. Either you are using python or any other language, finding the string length is one of the most commonly faced problems during software development.

In python, finding the length of a string is really easy. We have one default method to find out the length. We can either calculate the length using a loop or using the library function. In this tutorial, we will learn how to find the length of a string in python using two different ways :

The source code is available here.

1. Using a loop :

Note that this method is not recommended to find the length of a string. Because we already have one library method to find it. I will explain it to you later. Let’s try to find the length using a loop first :

python find length of string

python find string length

Explanation :

The commented numbers in the above program denote the step numbers below :

1. given_str is the given string. We need to find out the length of this string.
2. Create one integer variable size and assign it a value 0.
3. Using a for loop, run through each character of the string one by one. For each character, increment the variable size by 1.
4. Finally, print out the size of the string.

2. Using len() :

Instead of writing a for loop to find the length of a string, we can also use one inbuilt method len() to find out the length of a string in python. Let me show you with an example using the same string as shown in the Step-1 :

python find length of string

python find string length

As you can see that instead of writing a for loop, we can find out the length of a string using the method len().

Conclusion :

In this tutorial, we have learned two different ways to find out the length of a string in python. You can go for any of the methods explained above, but the second one i.e. len() is recommended. Try to find the length of different strings and drop one comment below if you have any queries.

You might also like :

Leave a Reply