Count spaces in a string in Python

Introduction: –

In this tutorial, you will learn how to find the number of spaces in a given string in Python.

The process that determines the number of space characters (‘ ‘) present in a given string is called Count spaces. This can be useful in various scenarios, such as text processing, data cleaning, and formatting tasks where the number of spaces might be significant.

There are various methods to count the spaces in Python, such as

  • using ‘ str. count() ‘
  • using a loop
  • using List Comprehension
  • using ‘ sum() ‘ and a Generator Expression, etc…

But mostly Two methods are Preferable :

Method 1:- Using ‘ str. count() ‘

Python has a built-in method called count(), which helps to keep the count of spaces in the string. To count spaces, you can pass a space character (‘ ‘) as an argument to this method.

Example :-

str = " This is an example "
space_count = str. count(' ')
print(space_count)
Output:-
3

From the above example, we have considered the String ” This is an example “.

Here 3 spaces separate the words “This”, “is”, “an”, and “example”.

If we look at the count(), a space is the parameter that is specified to be counted, which is given within a single quotation.

The count() method returns an integer with the number of occurrences.

Method 2:- Using a Loop

For loop can be used to iterate through the string and increments.

str = " This is an example."
space_count = 0
for char in str:
     if char == ' ':
        space_count += 1
print(space_count)
Output:-
3

The code snippet prints the output 3.

The space counts every time a space character is found in the string.

 

Leave a Comment

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

Scroll to Top