If you really only want to coalesce hyphens, use the other suggestions. Otherwise you can write your own function, something like this:
>>> def coalesce(x):
... n = []
... for c in x:
... if not n or c != n[-1]:
... n.append(c)
... return ''.join(n)
...
>>> coalesce('My---sun--is------very-big---.')
'My-sun-is-very-big-.'
>>> coalesce('aaabbbccc')
'abc'
If you really only want to coalesce hyphens, use the other suggestions. Otherwise you can write your own function, something like this:
How about:
the regular expression
"-+"
will look for 1 or more"-"
.As usual, there's a nice
itertools
solution, usinggroupby
:If you want to replace any run of consecutive characters, you can use
If you only want to coalesce non-word-characters, use
If it's really just hyphens, I recommend unutbu's solution.
Another simple solution is the String object's replace function.