计算字符串中的连续字母如果值为1,则该值应为空?

2024-10-02 22:32:24 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有字符串“abbcccd”,那么它应该显示“ab2c3d” 同样,我需要得到输出?你知道吗


Tags: 字符串abbcccdab2c3d
1条回答
网友
1楼 · 发布于 2024-10-02 22:32:24

我的努力。在循环期间使用临时字符串作为引用非常简单。你知道吗

s = 'abbcccd'
new = ''
temp = ''
for i, letter in enumerate(s):
    if i == 0:
        temp += letter
        continue
    if letter == temp[-1]:
        temp += letter
    elif letter != temp[-1]:
        new += temp[-1]
        if len(temp) > 1:
            new += str(len(temp))
            temp = letter

new += temp[-1]
if len(temp) > 1:
    new += str(len(temp))

因此,您应该得到:

print (s)
>>>'ab2c3d'

相关问题 更多 >