Write a Python function that takes a string and encode it that the amount of symbols would be represented by integer and the symbol.


Topic: Write a Python function that takes a string and encode it that the amount of symbols would be represented by integer and the symbol.

Solution

For example, the string "AAAABBBCCDAAA" would be encoded as "4A3B2C1D3A"
def encode_string(str1):
    encoded = ""
    ctr = 1
    last_char = str1[0]
    for i in range(1, len(str1)):
        if last_char == str1[i]:
            ctr += 1
         
        else:
            encoded += str(ctr) + last_char
            ctr = 0
            last_char = str1[i]
            ctr += 1
    encoded += str(ctr) + last_char
    return encoded



List all Python Programs