我有三个字符串,如下所示:
string1 = 'dddlll'
string2 = 'ddlldds'
string3 = 'lllllddsss'
我想得到这样的结果:
result1 = 'd3l3' # The first '3' stands for the number of 'd', and the second '3' stands for the number of 'l'
result2 = 'd2l2d2s1'
result3 = 'l5d2s3'
有人可以帮助我在Python3中做到这一点吗?非常感谢您的帮助!
答案 0 :(得分:0)
对于您的特殊情况,我会说您需要一个遍历单词的函数,您可以使用:
def letter_counter(string):
endstring = ''
prev_letter = ''
counter = ''
for letter in string + str(0):
if prev_letter != letter:
endstring = endstring + prev_letter + str(counter)
prev_letter = letter
counter = 1
else:
counter += 1
return endstring
letter_counter(string1)
'd3l3'
如果只希望每个字母都带有计数,则可以使用collections.Counter
并创建一个自定义函数,例如:
from collections import Counter
def letter_counter(string):
endstring = ''
for k,v in Counter(string).items():
endstring = endstring + k + str(v)
return endstring
letter_counter(string1)
'd3l3'