easy +10 pts

Caesar Cipher Shift

Shift each letter in a string by a given number of positions in the alphabet.

Write a function `caesar_cipher(text: str, shift: int) -> str` that takes a string `text` and an integer `shift`, and returns a new string where each alphabetic character is shifted by `shift` positions in the English alphabet (a–z or A–Z). The shift wraps around, so 'z' shifted by 1 becomes 'a'. Non-alphabetic characters (digits, punctuation, spaces) remain unchanged. The case of letters must be preserved. The shift can be any integer (positive, negative, or zero).

Constraints

The input text will contain at most 10^5 characters. The shift will be in the range -10^9 to 10^9.

Example

>>> caesar_cipher("abc", 1)
'bcd'
>>> caesar_cipher("XYZ", 3)
'ABC'
>>> caesar_cipher("Hello, World!", 5)
'Mjqqt, Btwqi!'
>>> caesar_cipher("abc", -1)
'zab'
10 points ~15 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Use the ASCII codes of characters and modulo arithmetic to wrap around the alphabet.
Check if a character is alphabetic using `char.isalpha()`.
Convert shift to a value in [0, 25] using `shift % 26` before applying it.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.