How to remove duplicates only if consecutive in a string?

Viewed 27407

For a string such as '12233322155552', by removing the duplicates, I can get '1235'.

But what I want to keep is '1232152', only removing the consecutive duplicates.

9 Answers

This would be a way:

def fix(a):
    list = []

    for element in a:
        # fill the list if the list is empty
        if len(list) == 0:list.append(element)
        # check with the last element of the list
        if list[-1] != element:  list.append(element)

    print(''.join(list))    


a= 'GGGGiiiiniiiGinnaaaaaProtijayi'
fix(a)
# output => GiniGinaProtijayi
Related