Search code examples
pythonlistpython-2.7encryptiondecoder

How to make Caesar decoder circular in Python (2.7)?


After much frustration, I have made my first Caesar Decoder :)

But the problem now is to make the program circular...

For example if we want to shift doge by 1, no problem, it's ephf...

But what about xyz, and the shift was 4???

So programming pros help a first time novice aka newb out :P Thanks...

import string
def main():        
    inString = raw_input("Please enter the word to be "
                         "translated: ")
    key = int(raw_input("What is the key value? "))

    toConv = [ord(i) for i in inString] #now want to shift it by key
    toConv = [x+key for x in toConv]
    #^can use map(lambda x:x+key, toConv)
    result = ''.join(chr(i) for i in toConv)

    print "This is the final result due to the shift", result

Solution

  • Just add the key to all the actual character codes, then if the added value is greater than z, modulo with character code of z and add it with the character code of a.

    inString, key = "xyz", 4
    toConv = [(ord(i) + key) for i in inString] #now want to shift it by key
    toConv = [(x % ord("z")) + ord("a") if x > ord("z") else x for x in toConv]
    result = ''.join(chr(i) for i in toConv)
    print result   # cde