How to replace multiple spaces in a string with a single space between words in Python

1 Answer

0 votes
import re

def replace_multiple_spaces(string):
    # Use a regular expression to replace multiple spaces with a single space
    result = re.sub(r'\s+', ' ', string)
    
    # Optionally trim leading and trailing spaces
    return result.strip()

string = "   This   is    a   string   with   multiple    spaces   "
output_string = replace_multiple_spaces(string)

print(f"\"{output_string}\"")




'''
run:

"This is a string with multiple spaces"

'''

 



answered Apr 4 by avibootz
...