Count the number of spaces in a string in Python
In this tutorial, we will learn how to count the number of spaces in a given string in Python.
Before proceeding to the solution, let us understand the problem first with a simple example:
Consider an input string with several blank spaces. Our task is to count the number of spaces in the given string. The built-in string method isspace() returns True value if it encounters a space in the string. By using a counter value initialized to zero, and incrementing it whenever isspace() returns True value, one can easily find the count of the number of spaces in a string.
isspace() method in Python
Before moving on with the implementation, let’s learn in detail about the isspace() method:
inputstring.isspace() returns Ture if at least, it contains one character and has only whitespace characters in it, otherwise False. The whitespace characters can be a separator space or bidirectional class member such as whitespace, blank or space.
Program to count the number of spaces in a string in Python
count=0 line="Codespeedy Technology Private Limited" for i in line: if(i.isspace()): count=count+1 print("The number of blank spaces is: ",count)
Output:
The number of blank spaces is: 3
This code illustrates how to count the number of spaces in a string. Firstly, initialize a count variable to zero and consider an input string. Then, iterate through each character in the string using a for loop and check for each of those characters whether it is a space using an in-built string method isspace(). Increment the count variable whenever space is encountered and isspace() returns True. Lastly, the number of spaces in the string is printed.
I hope this post helped to solve your doubts. Happy learning folks!
Recommended Blogs:
List of all Keywords in Python
Trigonometric and Angular functions in Python
Leave a Reply