Count number of spaces in a string in Python

If you don’t know how to count the spaces in a string using Python this tutorial is for you.

In this tutorial, we will learn how to count spaces in a string in Python using some examples. Don’t worry I will make it as simple as to understand perfectly without any confusion.

The purpose is to count the space ” ” in a string by giving user input

What are the main functions here :

  1. User input: we take input from the user
  2. Then count the number of spaces between the string
  3. Then finally prints the number of spaces in the provided string.

Let me show you with the code snippets

s=input() #taking input from the user

Here s is the string parameter

This asks the user to enter a string and store it in the variable ‘s’.

c=0 #initializing c variable from 0 to count number of spaces

 

Here we are initializing a variable c to zero, this helps us to count the number of spaces in a string.

for i in s: #iterating through string
 if i == ' ':#checking whether the character is space or not
  c+=1 # if character is space increase c value by 1

This snippet checks each character in the string

Let me explain the snippet:

  • For each character i in the string s
  • This checks if there is a character or space in the provided or given input string
  • If there is a space (c+=1) increment the c by 1, by representing there is a space
print("The number of spaces in the given string are: ",c)  #prints number of spaces

This prints the total number of spaces found in the given string.

OUTPUT: The message indicating the number of spaces in the given string are: —prints no. of spaces

Code:

s=input("Give a string: ") #taking input from the user
c=0 #initializing c variable from 0 to count number of spaces
for i in s: #iterating through string
 if i == ' ': #checking whether the character is space or not
  c+=1 # if character is space increase c value by 1
print("The number of spaces in the given string are: ",c)  #prints number of spaces

Output:

Give a string :venkata dinesh usarti
The number of spaces in the given string are: 2

 

I think you have got to know how to count the number of spaces in a string using Python by this tutorial. Thank you.

Leave a Reply

Your email address will not be published. Required fields are marked *