easy +10 pts

XOR Cipher Encode

Implement a classic XOR cipher that encrypts plaintext with a single key character.

Write a function `xor_encrypt(plaintext: str, key: int) -> str` that returns the ciphertext string produced by XORing each plaintext character's ordinal value with the integer `key`. The key is a non-negative integer between 0 and 255. For each character `c` in `plaintext`, compute `ord(c) ^ key`, convert the result to a character with `chr`, and concatenate all resulting characters to form the ciphertext. The input `plaintext` may be empty, and may contain any printable ASCII characters (including spaces, digits, punctuation). The function should work for any key in the given range, and the output is a string. Do not modify the key or plaintext.

Constraints

- `plaintext`: a string, length between 0 and 1000, containing printable ASCII characters (code points 32–126). - `key`: an integer, 0 ≤ key ≤ 255. - Time complexity: O(n) where n is the length of the string. - Space complexity: O(n) for the result.

Example

>>> xor_encrypt('hello', 32)
'HELLO'
>>> xor_encrypt('ABC', 0)
'ABC'
>>> xor_encrypt('', 7)
''
>>> xor_encrypt('abc', 1)
'`cb'
10 points ~10 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Use a loop or a generator expression with `ord` and `chr`.
Remember that XOR is a bitwise operation: `ord(c) ^ key`.
For an empty string, the result is an empty string.
The key is an integer that can be used directly in the XOR operation.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.