Python 3 program to count the total number of characters in a string

Write a python 3 program to count the total number of characters in a String :

In this example, we will learn how to write a python 3 program to count the total number of characters of a string. We are not going to count any space,tabs or newline . For example, ‘Hello World’ will return 10. Let’s take a look into the program :

Python 3 Program :

input_string = input("Enter a string : ")

count = 0

for c in input_string :
	if c.isspace() != True:
		count = count + 1

print("Total number of characters : ",count)

Sample Outputs :

Enter a string : This   string	has	four	tabs
Total number of characters :  21

Enter a string : This string has four space
Total number of characters :  22

In the above example, first string contains ‘tabs’ and the second string contains ‘spaces’ . But you can see that space and tabs are not counted on both cases.

Here, we are storing the total value in the variable ‘count’. We are iterating the string character by character. To check if a character is blank character, we are using ‘isspace()’ method. If it is false, means the character is non-empty . Increment the value of ‘count’ for this .

Sitewide-USD 336x280

Leave a Reply