Python program to count the number of blank spaces in a text file

Blank spaces in a text file refer to the empty spaces or gaps between words, sentences, or characters. These spaces are typically represented by the space character (' ') or other whitespace characters, including tab ('\t'), newline ('\n'), carriage return ('\r'), form feed ('\f'), and vertical tab ('\v'). These characters, as per the Unicode standard, represent empty space or formatting elements in the text.

When counting the number of blank spaces in a text file, we are essentially looking for these whitespace characters to determine the frequency or distribution of spaces within the text. This information can be useful for various purposes, such as text analysis, data cleaning, or formatting adjustments.

In this article, we will see different approaches to counting the number of blank spaces in a text file using Python programming.

Using the count() Method

The count() method is a built-in method in Python that is available for string objects. It allows us to count the number of occurrences of a specified substring within a string.

Following is the syntax of the count() method ?

string.count(substring, start, end)

Where,

  • string ? This is the original string on which we want to perform the counting

  • substring ? This is the substring that we want to count within the original string.

  • start (optional) ? This is the starting index from where the search for the substring should begin. By default, it starts from index 0.

  • end (optional) ? This is the ending index where the search for the substring should stop. By default, it searches until the end of the string.

The method returns an integer value representing the number of occurrences of the specified substring within the original string.

Example

In this example, we will use the count() method to count the number of blank spaces in a text file ?

# Create a sample text file for demonstration
with open('sample_document.txt', 'w') as f:
    f.write("This is a sample text file.\nIt contains multiple lines.\nEach line has spaces between words.")

def count_blank_spaces(file_path):
    count = 0
    with open(file_path, 'r') as file:
        for line in file:
            count += line.count(' ')
    return count

# defining the text file path
file_path = 'sample_document.txt'
blank_space_count = count_blank_spaces(file_path)
print(f"Number of blank spaces in the file: {blank_space_count}")
Number of blank spaces in the file: 14

Using the isspace() Method

The isspace() method is a built-in string method in Python that checks whether a character is a whitespace character. It returns True if the character is whitespace, and False otherwise. This method can identify all types of whitespace characters, not just spaces.

Example

Here's an example that counts the number of blank spaces in a text file using the isspace() method ?

# Create a sample text file for demonstration
with open('sample_document.txt', 'w') as f:
    f.write("This is a sample text file.\nIt contains multiple lines.\nEach line has spaces between words.")

def count_blank_spaces(file_path):
    count = 0
    with open(file_path, 'r') as file:
        for line in file:
            count += sum(1 for char in line if char.isspace())
    return count

# defining the text file path
file_path = 'sample_document.txt'
blank_space_count = count_blank_spaces(file_path)
print(f"Number of blank spaces in the file: {blank_space_count}")
Number of blank spaces in the file: 16

Note: The isspace() method counts all whitespace characters including newlines, which is why the count is higher than the previous method.

Using the re.findall() Function

In this approach, we will utilize the re.findall() function from the re module to find all occurrences of whitespace characters in the text file. The regular expression "\s" matches any whitespace character, including spaces, tabs, and newlines.

Example

Let's see the below example to count the number of blank spaces in a text file using the re.findall() method ?

import re

# Create a sample text file for demonstration
with open('sample_document.txt', 'w') as f:
    f.write("This is a sample text file.\nIt contains multiple lines.\nEach line has spaces between words.")

def count_blank_spaces(file_path):
    with open(file_path, 'r') as file:
        text = file.read()
        count = len(re.findall(r'\s', text))
    return count

# defining the text file path
file_path = 'sample_document.txt'
blank_space_count = count_blank_spaces(file_path)
print(f"Number of blank spaces in the file: {blank_space_count}")
Number of blank spaces in the file: 16

Comparison of Methods

Method Counts Only Spaces Counts All Whitespace Memory Usage
count(' ') Yes No Low
isspace() No Yes Low
re.findall() No Yes High (loads entire file)

Conclusion

Use count(' ') to count only space characters efficiently. Use isspace() or re.findall() to count all whitespace characters including tabs and newlines. The count() method is most memory-efficient for large files.

Updated on: 2026-03-27T13:52:50+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements