Search code examples
pythonpython-3.xascii

How to keep spaces and special characters while encoding a sentence


So I'm trying to make an encoding/decoding program, that lets the user to type a sentence and turn it into an encoding message by replacing letters with other letters.

It works fine with one words, but when I put more words with spaces and special characters it seems to be not working.

So here is my code:

 phrase = input("Write a sentence:")
decalage = int(input("By how many letters (1 to replace a with b...): "))

maping = {}
for i in range(26):
    i_cesar = (i + decalage) % 26
    c_cesar = chr(i_cesar + ord('a'))
    c = chr(i + ord('a'))
    maping[c] = c_cesar

result = ""
for c in phrase:
   result = result + maping[c]
print(result)

Solution

  • You're only building a mapping for the lowercase letters. One thing you can do is make a string of all the characters you intend to change, then rotate a copy of that string to form your dictionary.

    from string import ascii_lowercase, digits, punctuation
    
    characters = ascii_lowercase + digits + punctuation
    
    def rotate(s: str, degree: int) -> str:
        return s[degree:] + s[:degree]
    
    def cesar_encode(plaintext: str, cipher: int) -> str:
        mapping = dict(zip(characters, rotate(characters, cipher)))
        return "".join([mapping.get(c, c) for c in plaintext])
    
    cesar_encode("abcde12345$%^&", 1)
    # "bcdef23456%&_'"