Python String – Replace Multiple Spaces with Single Space

Replace multiple Whitespaces with single space in a String

To replace multiple white spaces with single space, you could you regular expression module function re.sub(), or you can use string split() and join() functions.

In this tutorial, we shall go through each of these approaches and learn how to replace multiple white spaces with a single space character, with example programs.

Approach 1: Using re.sub() function

re.sub() function can be used with the regular expression r'\s+', which matches one or more whitespace characters (including spaces, tabs, and newlines). All the matches found have to be replaced with a single space ' '. This way, any sequence of multiple spaces will be replaced with a single space.

Python Program

import re

# Given string
input_string = 'apple    banana        cherry'

# Replace multiple spaces with single space
output_string = re.sub(r'\s+', ' ', input_string)

print(output_string)
Run Code Copy

Output

apple banana cherry

Approach 2: Using string split() and join() functions

The following is a quick code snippet to replace multiple spaces with a single space using string split() and string join() functions.

" ".join(input_string.split())

By default, the split() function splits the string with space as delimiter. Once we get all the chunks, we can then join them again with a single space. The resulting string is what we desire, free of multiple adjacent spaces.

In the following example, we will take a string that has multiple white spaces occurring continuously at some places. And then we will use split() and join() functions to replace those multiple spaces with a single space.

Python Program

# Given string
input_string = 'apple    banana        cherry'

# Replace multiple spaces with single space
output_string = " ".join(input_string.split())

print(output_string)
Run Code Copy

Output

apple banana cherry

Even if there are any leading or trailing spaces in the string, they would be trimmed out while splitting the string.

Let take an input string that has multiple white spaces including the white space characters like new line, new tab, etc.

Python Program

# Given string
input_string = 'apple \t\t\n   banana    \t \n    cherry'

# Replace multiple spaces with single space
output_string = " ".join(input_string.split())

print(output_string)
Run Code Copy

Output

apple banana cherry

All the adjacent white space characters, including characters like new line, new tab, etc., are replaced with a single space. The same demonstration should hold for other white space characters like line feed, thin space, etc.

Summary

In this tutorial of Python Examples, we learned how to replace multiple spaces with a single space, using re.sub() function, or string split() and string join() functions.

Related Tutorials

Code copied to clipboard successfully 👍