Python Program to Calculate the Length of a String Without Using a Library Function

When it is required to calculate the length of a string without using library methods, a counter is used to increment every time an element of the string is encountered.

Below is the demonstration of the same ?

Example

my_string = "Hi Will"
print("The string is :")
print(my_string)

my_counter = 0
for i in my_string:
    my_counter = my_counter + 1

print("The length of the string is")
print(my_counter)

Output

The string is :
Hi Will
The length of the string is
7

Using While Loop

Another approach is to use a while loop with try-except to access characters by index ?

my_string = "Hello World"
print("The string is :")
print(my_string)

length = 0
try:
    while True:
        my_string[length]
        length += 1
except IndexError:
    pass

print("The length of the string is")
print(length)
The string is :
Hello World
The length of the string is
11

Using Recursion

We can also calculate string length using a recursive function ?

def get_string_length(text, index=0):
    try:
        text[index]
        return 1 + get_string_length(text, index + 1)
    except IndexError:
        return 0

my_string = "Python"
print("The string is :")
print(my_string)

length = get_string_length(my_string)
print("The length of the string is")
print(length)
The string is :
Python
The length of the string is
6

Explanation

  • A string is defined and displayed on the console.

  • A counter is initialized to 0.

  • The string is iterated over, and after every element is encountered, the counter is incremented by 1.

  • This counter value represents the length of the string and is displayed as output.

Conclusion

The for loop approach is the most readable and efficient method. Use while loop with try-except for educational purposes, and recursion when demonstrating recursive problem-solving techniques.

Updated on: 2026-03-25T19:13:34+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements