Python program to find string length

In this program we will learn how to calculate the number of characters in a word (or a string). To understand this program,
you should have the knowledge of following topics in python

  • Strings
  • for in loop

program

 

In this program, we are allowing a user to enter his/her name and then we will find out the number of characters in that name.

username = input("Enter your name -")
count = 0 
for x in username:
    count+=1
print("The number of characters is", count)

Output

Enter your name - vasu

The number of characters is 4

Explanation

  • First of all, we have displayed a message- “Enter your name”. The name or whatever the user enters would be stored inside the variable ‘username’ in the form of a string.
  • Then we have declared a variable named ‘count’ and we have initialized it with 0. We will use this variable to calculate the number of characters.
  • Then we have executed a ‘for in’ loop for the string stored in ‘username’. This will first break the string in single characters and the loop will run on individual characters. For example – if the string is ‘John’, the loop will break it in j,o,h,n and then the loop will run for each character. In this particular case, the loop will run for four times.
  • For every iteration, we are incrementing the value of variable ‘count’ by 1. Because the loop would execute for every character, the value of  ‘count’ variable would be incremented by 1 for the same number of times. For example if the string has four characters. The count variable would be incremented four times and finally has value 4. Something like this –

For first iteration – count = 0 + 1 => count = 1

For second iteration – count = 1 + 1 => count = 2

For third iteration – count = 2 + 1 => count = 3

For fourth iteration – count = 3 + 1 => count = 4

  • The final value that is stored inside the variable ‘count’ would then be displayed, which is the actual count of the characters in the string.