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

 Live Demo

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

Explanation

  • A string is defined, and is displayed on the console.

  • A counter is initialized to 0.

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

  • This is displayed as output on the console.

Updated on: 17-Apr-2021

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements