美文网首页
字符串简化

字符串简化

作者: 领带衬有黄金 | 来源:发表于2021-10-15 16:25 被阅读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))
    
    

    相关文章

      网友评论

          本文标题:字符串简化

          本文链接:https://www.haomeiwen.com/subject/cdpmoltx.html