How to Replace Multiple Spaces with Single Space in Python String?

17-Mar-2023

.

Admin

How to Replace Multiple Spaces with Single Space in Python String?

Hi Dev,

This post is focused on how to replace multiple spaces with a single space in a python string. you'll learn python to replace multiple spaces with a single space. Here you will learn python string to replace multiple spaces with one. we will help you to give an example of a python string replacing multiple whitespaces with one.

In this example, I will add myString variable with the hello string. Then we will use the sub() function of the re library to replace multiple spaces with one from a string in python. So, without further ado, let's see simple examples: You can use these examples with the python3 (Python 3) version.

Example


main.py

import re

# Declare String Variable

myString = "Hello, This is nicesnippets.com. This is awesome."

# Python replaces multiple spaces with single space

replaceString = re.sub(' +', ' ', myString)

print(replaceString)

Output:

Hello, This is nicesnippets.com. This is awesome.

#Python