Replacing repeated consecutive characters in Python

后端 未结 5 684
抹茶落季
抹茶落季 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 06:03

    Using a simple iteration.

    Demo:

    def cleanText(val):
        result = []
        for i in val:
            if not result:
                result.append(i)
            else:
                if result[-1] != i:
                    result.append(i)
        return "".join(result)
    
    s = ['hiiii how are you??', 'aahhhhhhhhhh whyyyyyy', 'foo', 'oook. thesse aree enoughh examplles.']
    for i in s:
        print(cleanText(i))
    

    Output:

    hi how are you?
    ah why
    fo
    ok. these are enough examples.
    

提交回复
热议问题