Python – Replace Multiple White Spaces with Single Space

Replace multiple Whitespaces with single space in a String

To replace multiple white spaces with single space, you could implement the following process.

  1. split() the string with default separator
  2. then use join() with a single space

In this tutorial, we shall learn how to replace multiple white spaces with a single space character, with the help of well detailed example programs.

Sample Code

Following is a quick code snippet to replace multiple spaces with a single space.

" ".join(mystring.split())

where mystring contains continuous multiple white spaces.

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.

Examples

1. Replace continuous multiple white spaces with single space

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.

Python Program

mystring = 'welcome    to  python        examples'

correctedstring = " ".join(mystring.split())
print(correctedstring)
Run Code Copy

Output

welcome to python examples

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

2. Replace continuous multiple white spaces, containing \n, \t, etc

In the following example, we will take a string that has multiple white spaces including the white space characters like new line, new tab, etc. We shall apply the steps mentioned in the introduction, and observe the result.

Python Program

mystring = 'welcome \t\t   to  python  \n\n      examples'

correctedstring = " ".join(mystring.split())
print(correctedstring)
Run Code Copy

Output

welcome to python examples

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

Summary

In this tutorial of Python Examples, we learned how to replace multiple white characters with a single space, using split() and join() functions.

Code copied to clipboard successfully 👍