'Encoding a cipher

Question: It’s time to practice our spy craft and encode a simple cipher. Write a function encode() that asks the user for the message to be encoded and for an integer key value. The cipher will shift each character in the message by adding the key to the character’s Unicode value. For example, ‘A’ (unicode 65) shifted 3 produces ‘D’ (unicode 68).

Please make sure your output is only the cipher text.

The output should be:

enter a message: The time has come, the Walrus said

enter a key: 7

[ol'{ptl'ohz'jvtl3'{ol'^hsyz'zhpk



Solution 1:[1]

You can use chr() and ord() to shift each character and join() to put the result back together:

s = "The time has come, the Walrus said"
k = 7

e = "".join(chr(ord(c)+k) for c in s)

print(e)
[ol'{ptl'ohz'jvtl3'{ol'^hsy|z'zhpk

Solution 2:[2]

This is a simple caesar cipher Here is the code anyway

def encrypt(text, s):
    result = ""
    # transverse the plain text
    for i in range(len(text)):
        char = text[i]
        # Encrypt uppercase characters in plain text
        if (char.isupper()):
            result += chr((ord(char) + s-65) % 26 + 65)
        # Encrypt lowercase characters in plain text
        else:
            result += chr((ord(char) + s - 97) % 26 + 97)
    return result

Solution 3:[3]

You could consider using chr, ord, and str.join(iterable):

def get_int_input(prompt: str) -> int:
    while True:
        try:
            return int(input(prompt))
        except ValueError:
            print('Error: Enter an integer, try again...')


def encode(message: str, key: int) -> str:
    return ''.join(chr(ord(ch) + key) for ch in message)


def main() -> None:
    message = input('Enter a message: ')
    key = get_int_input('Enter a key: ')
    encoded = encode(message, key)
    print(encoded)

    
if __name__ == '__main__':
    main()

Example Usage:

Enter a message: The time has come, the Walrus said
Enter a key: 7
[ol'{ptl'ohz'jvtl3'{ol'^hsy|z'zhpk

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Alain T.
Solution 2
Solution 3