Python ASCII to RLE (compression) example

by james

In this blog i will be covering a simple way of compressing plain ASCII text to RLE(Run Length Encoding), using python .
The main process followed to complete the task is:

  • given the example 'ab' as a plain ASCII input string
  • get the first character ('a')
  • test if it was the same as the previous one (there is no previous character)
  • if it was then we increment the counter by 1
  • if it wasn't we test if there was a previous character if so then we store it
    • e.g. previous character was 'a' and count was '1' 
    • so we store this in our encoding string as '01a'
  • if the previous character had no value then we do nothing
  • reset the counter to 1 so we can loop through again 

 

def asciitoRLE(a):
    counter=0
    cstring=""
    prevChar=""1
    #get the length of the input string
    length=len(a)  
    # loop throught the input string compressing as we go along
    for i in range(length):
        #get the next character
        x=a[i]
        #is this char the same as the last one
        if x== prevChar:
            #yes: increment counter
            counter=counter +1
        else:
            #no: so this is a new char, is there anything in the prev character
            if prevChar=="":
                #no: do nothing
                prevChar=prevChar
            else:
                #yes: store what we have in cstring
                cstring= cstring+ str(counter).rjust(2, '0')+prevChar 
            #reset counter for next character
            counter=1
            #and store this character in prevchar
            prevChar=x
    
    cstring= cstring+ str(counter).rjust(2, '0')+prevChar
    return(cstring)

 

In the function above asciitoRLE it takes one parameter, the ascii text which the user inputs.

EXMAPLE: "aaabbc"