Search code examples
pythonindexingasciiindicescaesar-cipher

Using an index range to search ascii


I am trying to search through the ascii index to write a caesar cipher program with the range being >= 32 and <= 126. When I get to the last print out I get some characters that are not in that range. I have tried for loops and while loops, but keep getting errors.

I apologize if I did not post this properly. It is my first post.

Thanks for any help.

    def cipher(phrase,shift):

        x = list(str(phrase))
        xx = ''.join(list(str(phrase)))

        yy = []
        print(x)
        for c in xx:
            yy.append(chr(ord(c)+shift))

        return ''.join(yy)

    print(cipher('ABCDE', 97 - 65))
    print(cipher('abcde', 65 - 97))
    print(cipher(' !\"#$', 95))     

and my output is:

['A', 'B', 'C', 'D', 'E']
abcde
['a', 'b', 'c', 'd', 'e']
ABCDE
[' ', '!', '"', '#', '$']

Solution

  • This should work (note that I cleaned your code up a bit):

    def cipher(phrase, shift):
    
        x = list(str(phrase))
        yy = ''
        print(x)
        for c in phrase:
            dec = ord(c) + shift
            while dec < 32:
                dec = 127 - (32 - dec)
            while dec > 126:
                dec = 31 + (dec - 126)
            yy += (chr(dec))
    
        return yy
    
    print(cipher('ABCDE', 97 - 65))
    print(cipher('abcde', 65 - 97))
    print(cipher(' !\"#$', 95))
    

    The output is:

    ['A', 'B', 'C', 'D', 'E']
    abcde
    ['a', 'b', 'c', 'd', 'e']
    ABCDE
    [' ', '!', '"', '#', '$']
     !"#$