Replacing repeated consecutive characters in Python

后端 未结 5 650
抹茶落季
抹茶落季 2021-01-23 05:02

I need to make a function that replaces repeated, consecutive characters with a single character, for example:

 \'hiiii how are you??\' -> \'hi how are you?\'         


        
5条回答
  •  [愿得一人]
    2021-01-23 05:57

    from collections import OrderedDict
    
    def removeDupWord(word):
       return "".join(OrderedDict.fromkeys(word))
    
    def removeDupSentence(sentence):
        words = sentence.split()
        result = ''
        return ''.join([result + removeDupWord(word) + ' ' for word in words])
    
    
    sentence = 'hiiii how are you??'
    print (removeDupSentence(sentence))
    
    >>> hi how are you? 
    

提交回复
热议问题