Search code examples
pythonpython-re

Transform "4CA2CACA" to "CCCCACCACA"


I have already tried this (as somebody told me on another question):

 import re

 def decode(txt):
     list = []
     for cnt, char in re.findall(r"([\d*])([^d])", txt):
         list.extend((char * (int(cnt) if cnt else 1)))
     list = "".join(list)
     return list

Example:

print(decode("2CACA2CACA3CACACA3CAC"))

This is what I get

CCCCCCCCCC

And this is what I need

CCACACCACACCCACACACCCAC

Solution

  • If you want to do it without any imports, then you could do something like this:

    x = '2CACA2CACA3CACACA3CAC0M'
    int_string = ""
    char_list = []
    for char in x:
        if char.isnumeric():
            int_string += char
            continue
        else:
            if not int_string:
                char_list.append(char)
            else:
                char_list.append(char * int(int_string))
            int_string = ""
    print("".join(char_list))
    

    This will work for any positive integers, even zero, as you can see in the above example.