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 −
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)
The string is : Hi Will The length of the string is 7
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.