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.