Remove multiple spaces from a string in Python

In this tutorial, we will learn how to remove multiple spaces from a string and replace them with a single space.

Replace multiple spaces with a single space in Python

First of all, we need to declare a string variable that has a string that contains multiple spaces.

my_string="My        name   is    Nitesh         Jhawar"

Here, you can see that multiple spaces between the words but only a single space are required.

So, first of all, we need to separate each word of the string. Here we use a function split().
This function breaks or splits a string into its words and returns a list with the words separated with a comma. It is stored in variable str.
Let’s print str to see the result.

str=my_string.split()  
print(str)

Output:

['My', 'name', 'is', 'Nitesh', 'Jhawar']

Now we got a list with comma separated words of my_string.



Next, We want to concatenate the items in list str to convert it into a string. But how do we do that?
In order to do that, we use a function join().

This function joins or concatenates the items in a list or tuple. To separate the items, we need to provide a separator.

Syntax:
separator.join(list_name)

new_string=" ".join(str)

Here separator is whitespace and new_string holds our result.
Let’s see the value of new_string.

My name is Nitesh Jhawar

 

Finally, Our code looks like this.

my_string="My        name   is    Nitesh         Jhawar"
str=my_string.split()  
print(str)
new_string=" ".join(str)
print(new_string)

Output:

['My', 'name', 'is', 'Nitesh', 'Jhawar']
My name is Nitesh Jhawar

 

People are also interested in learning,

Leave a Reply

Your email address will not be published. Required fields are marked *