Is there a cross-platform library that collapses a multiline string into a single-line string without repeating spaces?
I came up with some kind of snippet, but I wonder if there is a standard function that I could import, maybe even optimized in C?
def collapse(input): import re rn = re.compile(r'(\r\n)+') r = re.compile(r'\r+') n = re.compile(r'\n+') s = re.compile(r'\ +') return s.sub(' ',n.sub(' ',r.sub(' ',rn.sub(' ',input))))
PS Thanks for the good observations. ' '.join(input.split()) seems to be a winner, since it actually works about twice as fast in my case as compared to search-replace with the pre-compiled regular expression r'\s+' .
source share