Here are two methods that show how to count and print blank spaces in Python. The input is a text file. The program looks for blank spaces and counts them. In the end, it prints the number of blank spaces.

ON THIS PAGE

  1. How to count blank spaces using for loop
  2. How to count blank spaces using while loop

How to count blank spaces using for loop

The input file is my_text. The count gives you the blank spaces count.

my_text="my name is srini"
count=0
for i in my_text:
    if i == ' ':
        count += 1
        
print(count)

Output

3
** Process exited - Return Code: 0 **
Press Enter to exit terminal
Advertisements

How to count blank spaces using while loop

Using a while loop how to count blank spaces explained in the below python program.

my_text = "my name is srini"
i=0
count=0
while i < len(my_text):
    if my_text[i] == ' ':
        count += 1
    i += 1
print(count)

Output

3
** Process exited - Return Code: 0 **
Press Enter to exit terminal

Related