How to Replace Multiple Spaces with One in Python
You can replace multiple spaces in a string with a single space using the join
method along with the split
method.
Here’s a simple example to illustrate this:
def replace_multiple_spaces(input_string):
# Split the string by whitespace and join it back with a single space
return ' '.join(input_string.split())
# Example usage
input_string = "This is an example string."
result = replace_multiple_spaces(input_string)
print(result) # Output: "This is an example string."
Explanation:
split()
: This method splits the string into a list of words, using any whitespace as a delimiter. It automatically handles multiple spaces and removes any leading or trailing whitespace.join()
: This method takes the list of words and concatenates them into a single string with a specified separator—in this case, a single space (' '
).
This method efficiently reduces all sequences of whitespace to a single space.