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
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.