Python3字符串问题

时间:2018-11-03 06:58:17

标签: python-3.x

我有三个字符串,如下所示:

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中做到这一点吗?非常感谢您的帮助!

1 个答案:

答案 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'