Categories
Python Answers

How to remove multiple spaces in a string with Python?

Spread the love

Sometimes, we want to remove multiple spaces in a string with Python.

In this article, we’ll look at how to remove multiple spaces in a string with Python.

How to remove multiple spaces in a string with Python?

To remove multiple spaces in a string with Python. we can use the re.sub method.

For instance, we write:

import re

s = "The   fox jumped   over    the log."
new_s = re.sub("\s\s+", " ", s)
print(new_s)

We call re.sub with the "\s\s+" regex string to look for 2 or more spaces.

And we replace them with a single space character.

s is the 3rd argument of sub so we’re doing the replacement on s and returning the new string.

We assign the returned string to new_s.

Therefore, new_s is 'The fox jumped over the log.'.

Conclusion

To remove multiple spaces in a string with Python. we can use the re.sub method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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