Count Length of a String using Python

Finding the length of a string means counting the number of letters in a string. Python has a built-in len() function for this task, but what if you get a coding interview question to find the length of a string without using the len() function? It’s simple, we have to use a for loop. So if you want to learn how to write a Python program to count the length of a string, this article is for you. In this article, I’ll show you a tutorial on how to count the length of a string using Python.

Count Length of a String using Python

To count the length of a string using Python, we generally prefer to use the len() function, which is easy to use and understand. If you’ve never used this function before, here’s how you can use it for counting the length of a string:

# using the builtin function
text = "Aman"
print(len(text))

Now, what if you are asked in a coding interview to count the number of letters without using the len() function? If you get this question in any coding interview even without the condition about the len() function, I would recommend not using the len() function, because coding interviews are for showing your way of defining the solution to a problem. So here is how you can count the length of a string using Python without using the len() function:

# without using the builtin function
n = 0
text = "Aman"
for i in text:
    n = n+1
print(n)

In the above code, the value of n increases by one till the variable i iterates over the last letter of the string. Finally, n equals the number of letters present in the string.

Also, Read – C++ Program to Count Number of Letters.

Summary

So this is how you can write a Python program for counting the length of a string. Finding the length of a string means counting the number of letters in a string. I hope you liked this article on how to find the length of a string by using the Python programming language. Feel free to ask your valuable questions in the comments section below.

Default image
Aman Kharwal

Coder with the ♥️ of a Writer || Data Scientist | Solopreneur | Founder

Articles: 1237

Leave a Reply