In this article, we will discuss different ways to delete duplicate spaces from a string in Python.
Table Of Contents
Suppose we have a string that contains some duplicate whitespaces,
"This is a simple string"
After removing duplicate whitespaces from it, the final string should be like,
This is a simple string
There are different ways to do this. Let’s discuss them one by one,
Remove duplicate spaces from string using split() and join()
In Python, the string class provides a member function split(sep). it splits the string based on the given sep as the delimiter and returns a list of the words. By default it uses the whitespace character as delimeter and discard empty strings.
We can split the string into a list of words and then join back those words using single space as delimeter.
Frequently Asked:
- Replace Last N characters from a string in Python
- Convert list to string in python using join() / reduce() / map()
- Remove specific characters from a string in Python
- Replace all occurrences of a substring in string – Python
For example,
strValue = "This is a simple string" # Remove all duplicate spaces in string strValue = ' '.join( strValue.split() ) print(strValue)
Output:
This is a simple string
It removed all duplicate spaces from string in Python.
Remove duplicate spaces from string using Regex
In Python, the regex module provides a function to replace the contents of a string based on a matching regex pattern. The signature of function is like this,
sub(pattern, replacement_str, original_str)
It looks for the matches of the given regex pattern in the sting original_str and replaces all occurrences of matches with the string replacement_str.
A regex pattern “\s+” will match all the whitespaces in string. We can replace them by a single space character. This way we can replace duplicate spaces with single space.
For example,
import re strValue = "This is a simple string" # Regex pattern to match all whitespaces in string pattern = "\s+" # Remove all duplicate spaces in string strValue = re.sub(pattern, ' ', strValue ) print(strValue)
Output:
This is a simple string
It removed all duplicate spaces from string in Python.
Summary
We learned about two different ways to delete duplicate spaces from a string in Python.