Remove repeating characters from words

后端 未结 4 778
醉酒成梦
醉酒成梦 2020-12-09 20:23

I was wondering what is the best way to convert something like \"haaaaapppppyyy\" to \"haappyy\".

Basically, when parsing slang, people sometimes repeat characters

4条回答
  •  伪装坚强ぢ
    2020-12-09 21:10

    You should do it without reduce or regexps:

    >>> s = 'hhaaaaapppppyyy'
    >>> ''.join(['' if i>1 and e==s[i-2] else e for i,e in enumerate(s)])
    'haappyy'
    

    The number of repetitions are hardcoded to >1 and -2 above. The general case:

    >>> reps = 1
    >>> ''.join(['' if i>reps-1 and e==s[i-reps] else e for i,e in enumerate(s)])
    'hapy'
    

提交回复
热议问题