How to fix 'String index out of range' error

感情迁移 提交于 2019-12-07 01:03:27

You can iterate over the string, keeping a running counter and create your string as you go

s = 'aaaaggggtt'

res = ''
counter = 1

#Iterate over the string
for idx in range(len(s)-1):
    #If the character changes
    if s[idx] != s[idx+1]:
        #Append last character and counter, and reset it
        res += s[idx]+str(counter)
        counter = 1
    else:
        #Else increment the counter
        counter+=1

#Append the last character and it's counter
res += s[-1]+str(counter)
print(res)

Or you can approach this using itertools.groupby

from itertools import groupby

s = 'aaaaggggtt'

#Count numbers and associated length in a list
res = ['{}{}'.format(model, len(list(group))) for model, group in groupby(s)]

#Convert list to string
res = ''.join(res)

print(res)

The output will be

a4g4t2

simple way:

str1 = 'aaaaggggtt'

set1 = set(str1)

res = ''

for i in set1:

    res+=i+str(str1.count(i))

print(res)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!