Create a compress function in Python?

后端 未结 19 1221
感动是毒
感动是毒 2021-01-05 03:37

I need to create a function called compress that compresses a string by replacing any repeated letters with a letter and number. My function should return the shortened vers

19条回答
  •  庸人自扰
    2021-01-05 04:36

    string = 'aabccccd' output = '2a3b4c4d'

    new_string = " "
    count = 1
    for i in range(len(string)-1):
        if string[i] == string[i+1]:
            count = count + 1
        else:         
            new_string =  new_string + str(count) + string[i]
            count = 1 
    new_string = new_string + str(count) + string[i+1]    
    print(new_string)
    

提交回复
热议问题