Substitute multiple whitespace with single whitespace in Python [duplicate]

A simple possibility (if you’d rather avoid REs) is

' '.join(mystring.split())

The split and join perform the task you’re explicitly asking about — plus, they also do the extra one that you don’t talk about but is seen in your example, removing trailing spaces;-).

Leave a Comment