字符串简化
2021-10-15 本文已影响0人
领带衬有黄金
1. 需求 将aaabbcddcccccc->a3b2cd2c6
2. 代码
a = 'aaabbcddcccccc'
def test(s):
result = []
count = 1
for index in range(1, len(s)):
if s[index - 1] == s[index]:
count += 1
else:
result.append(s[index - 1])
if count != 1:
result.append(count)
count = 1
# if index == len(s) - 1:
# result.append(s[index])
# if count != 1:
# result.append(count)
else:
result.append(s[index])
if count != 1:
result.append(count)
return ''.join([str(i) for i in result])
if __name__ == '__main__':
print(test(a))