Python program to count the number of spaces in string
Given a string, the task is to write a Python program to count the number of spaces in the string.
Examples:
Input: "my name is geeks for geeks" Output: number of spaces = 5 Input: "geeksforgeeks" Output: number of spaces=0
Approach:
- Input string from the user
- Initialize count variable with zero
- Run a for loop i from 0 till the length of the string
- Inside for loop, check if s[i] == blank, then increment count by 1
- Outside for loop, print count
Example 1:
Python3
# create function that # return space count def check_space(string): # counter count = 0 # loop for search each index for i in range ( 0 , len (string)): # Check each char # is blank or not if string[i] = = " " : count + = 1 return count # driver node string = "Welcome to geeksforgeeks" # call the function and display print ( "number of spaces " ,check_space(string)) |
Output:
number of spaces 2
Example 2:
Python3
# create function that # return space count def check_space(string): # counter count = 0 # loop for search each index for i in string: # Check each char # is blank or not if i = = " " : count + = 1 return count # driver node string = "Welcome to geeksforgeeks, Geeks!" # call the function and display print ( "number of spaces " ,check_space(string)) |
Output:
number of spaces 3
Example 3: Using the count() function.
Python3
# Create function that # return space count def check_space(Test_string): return Test_string.count( " " ) # Driver function if __name__ = = "__main__" : Test_string = "Welcome to geeksforgeeks, Geeks!" # Call the function and display print (f "Number of Spaces: {check_space(Test_string)}" ) |
Output:
Number of Spaces: 3