如下图,在一串字符串里统计连续出现的字符,并将该字符出现的次数写在新的字符串里。如果该字符只出现一次,不需要计数。
仅供参考
def main(text):
result = []
last_c = None
count = 0
for c in text:
if last_c is None:
last_c = c
count = 1
result.append(c)
continue
if last_c == c:
count += 1
else:
if count > 1:
result.append(str(count))
last_c = c
count = 1
result.append(c)
if count > 1:
result.append(str(count))
return "".join(result)