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 =  re.sub(' +', ' ', 'The     quick brown    fox')

to call re.sub with the ' +' to match more than one space in the string and replace them with one space in 'The quick brown fox'.

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 *