In this python program, we have to check the length of a string, so we need to know what is a string in python. A string is a sequence of letters or characters, and we have to find its length. For that, we have to use a counter, and that counter will increment by one while we traverse through each character of the string.
After accepting the string from the user, we store that in a variable. Then use the for loop in python program till the end of the string. Use a variable count to increment in every loop iteration. Finally, print the counter value. and in Python, we didn't need to initialize the variable in the for loop
. Let us break the code.
STEP 1: We accept the string from the user using the input function in python programming and store it in a variable.
STEP 2: Initialize a counter as zero; this counter is used to increment the value while traversing the string.
STEP 3: Use a for loop
till the end of the string.
STEP 4: Increment the counter by one every time we move inside the for loop
till the string ends.
STEP 5: Print counter's value as the length of the string using print
in python language.
str = input("Enter any string: ")
count = 0 # initialize the counter to zero
for s in str: # Use a for loop till the string ends.
count = count + 1 # increment the counter by 1 every time control gets inside the for loop
print("Length of the string is:", count)
Enter any string : Hello Length of the string is: 5