Python – How to Replace multiple spaces with single space in Text File?

Python – Replace multiple spaces with single space in a Text File

There are many ways to replace multiple white spaces with a single space like using a string split or regular expression module. We will see each one of them with examples.

Method 1: Using Split String

  1. Read the input text file in read mode and output file in write mode.
  2. For each line read from then input file
    1. Split the given string using split() method. By default split() method splits with space as delimiter. When there are multiple spaces, those splits are ignored and hence we will get individual words.
    2. Join the splits using single space ‘ ‘.
    3. Write to the output file.
  3. Close input and output files.

Example

In the following example, we will replace multiple spaces with single space.

Python Program

fin = open("data.txt", "rt")
fout = open("out.txt", "wt")

for line in fin:
	fout.write(' '.join(line.split()))
	
fin.close()
fout.close()

Input file

Welcome to      www.pythonexamples.org. Here, you will     find python programs              for all        general use cases.

Output file

Welcome to www.pythonexamples.org. Here, you will find python programs for all general use cases.

All multiple white spaces in the text file are replaced with a single white space.

Method 2: Using Regular Expression

You can also use regular expression to find continuous multiple white spaces and replace them with a single space.

  1. Import re module. re for regular expression.
  2. Read the input Text file in read mode and output Text file in write mode.
  3. For each line read from text file, use re.sub() method. sub() substitutes or replaces a string with another string in the text provided.
  4. Close input and output files.

Example

In the following example, we will replace all multiple white spaces with single white space using re module.

Python Program

import re

fin = open("data.txt", "rt")
fout = open("out.txt", "wt")

for line in fin:
	fout.write(re.sub('\s+',' ',line))
	
fin.close()
fout.close()

Summary

In this tutorial of Python Examples, we learned how to replace multiple white space characters with a single space, using different approaches and example programs for each of them.