Home > Software design >  Encoding a cipher
Encoding a cipher

Time:02-21

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

CodePudding user response:

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

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


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

CodePudding user response:

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

CodePudding user response:

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
  • Related