Caesar Cipher Encryption

Hard ⏱ 18 min 27% acceptance ★★★★★ 4.5
Write caesar_cipher(s, shift) implementing a proper Caesar cipher: every alphabetic character is shifted by shift positions within the alphabet (wrapping from z back to a), preserving its original case. Non-alphabetic characters (spaces, punctuation, digits) pass through unchanged.

Examples

Example 1
Input
s = 'Hello, World!', shift = 3
Output
'Khoor, Zruog!'
Explanation

'H'->'K', 'e'->'h', ... wrapping happens for letters near the end of the alphabet, and punctuation is untouched.

Example 2
Input
s = 'xyz', shift = 3
Output
'abc'
Explanation

'x','y','z' wrap around past 'z' back to the start of the alphabet.

Constraints

  • shift can be any integer, including negative or larger than 26.

Topics

StringsCiphers

Companies

Goldman SachsDeutsche BankJPMorgan Chase

Hints

Hint 1

For a lowercase letter: (ord(ch) - ord('a') + shift) % 26 + ord('a'), then chr() it.

Hint 2

Do the same with a capital-A base for uppercase letters, and leave everything else as-is.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.