Suppose this string:
The fox jumped over the log.
Turning into:
Because @pythonlarry asked here are the missing generator based versions
The groupby join is easy. Groupby will group elements consecutive with same key. And return pairs of keys and list of elements for each group. So when the key is an space an space is returne else the entire group.
from itertools import groupby
def group_join(string):
return ''.join(' ' if chr==' ' else ''.join(times) for chr,times in groupby(string))
The group by variant is simple but very slow. So now for the generator variant. Here we consume an iterator, the string, and yield all chars except chars that follow an char.
def generator_join_generator(string):
last=False
for c in string:
if c==' ':
if not last:
last=True
yield ' '
else:
last=False
yield c
def generator_join(string):
return ''.join(generator_join_generator(string))
So i meassured the timings with some other lorem ipsum.
With Hello and World separated by 64KB of spaces
Not forget the original sentence
Interesting here for nearly space only strings group join is not that worse Timing showing always median from seven runs of a thousand times each.