Table of Contents
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.
#Given string whose length is to be found str1="Python is great!" print("The given String is:",str1) #calling our len() method to calculate #the length of str1 print("Length =",len(str1))
str1is 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:
#function that calculates length of the passed string def str_len(str1): c=0 #counter initialised as 0 for i in str1: c=c+1 #counter increased for each element return c #Given string whose length is to be found str1="JournalDev" print("The given String is:",str1) #calling our str_len() function to calculate #the length of str1 print("Length =",str_len(str1))
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=0which 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
forloop, 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.
- What is the max length of a python string – Stackoverflow question.