Python Program to Count Total Characters in a String

Write a Python program to Count Total Characters in a String using For Loop and While Loop with a practical example.

Python Program to Count Total Characters in a String Example 1

This python program allows the user to enter a string. Next, it counts the total number of characters inside this string using For Loop.

Here, we used Python For Loop to iterate every character in a String. Inside the For Loop, we are incrementing the total value for each character.

# Python Program to Count Total Characters in a String
 
str1 = input("Please Enter your Own String : ")
total = 0
 
for i in str1:
    total = total + 1
 
print("Total Number of Characters in this String = ", total)
Python Program to Count Total Characters in a String 1

Python Program to Count Characters in a String Example 2

This String Characters program is the same as the above example. However, in this Python code, we are using the For Loop with Range.

# Python Program to Count Total Characters in a String
 
str1 = input("Please Enter your Own String : ")
total = 0
 
for i in range(len(str1)):
    total = total + 1
 
print("Total Number of Characters in this String = ", total)

Python Count String Characters output

Please Enter your Own String : Tutorial Gateway
Total Number of Characters in this String =  16
>>> 
Please Enter your Own String : Python
Total Number of Characters in this String =  6

Python Program to Count Number of Characters in a String Example 3

This python program to count characters is the same as above. However, we just replaced the For Loop with While Loop.

# Python Program to Count Total Characters in a String
 
str1 = input("Please Enter your Own String : ")
total = 0
i = 0

while(i < len(str1)):
    total = total + 1
    i = i + 1
 
print("Total Number of Characters in this String = ", total)
Please Enter your Own String : Python Programming
Total Number of Characters in this String =  18