Skip to main content

py_whisper_cipher — Caesar Cipher Shift

Difficulty: easy

Write a function that creates a simple cipher by shifting letters in a string by a given amount. Non-alphabetic characters should remain unchanged. Case is preserved.

def whisper_cipher(text: str, shift: int) -> str:

Examples

>>> whisper_cipher("hello", 3)
"khoor"

>>> whisper_cipher("Hello World!", 1)
"Ifmmp Xpsme!"

>>> whisper_cipher("xyz", 3)
"abc"

>>> whisper_cipher("ABC123def", 5)
"FGH123ijk"

>>> whisper_cipher("", 10)
""

Solution

Download py_whisper_cipher.py
def whisper_cipher(text: str, shift: int) -> str:
result = []
for c in text:
if "a" <= c <= "z":
result.append(chr((ord(c) - ord("a") + shift) % 26 + ord("a")))
elif "A" <= c <= "Z":
result.append(chr((ord(c) - ord("A") + shift) % 26 + ord("A")))
else:
result.append(c)
return "".join(result)

How It Works

Goal: Apply a per-letter shift to the alphabet, wrapping around past z/Z, while preserving case and non-letters.

Approach: Map each letter to a 0..25 index, add the shift modulo 26, then map back to a character. Use separate branches for lowercase and uppercase to keep case.

Step by step:

  1. For each character, check whether it falls in the lowercase or uppercase range.
  2. Compute (ord(c) - base + shift) % 26 + base, where base is ord('a') or ord('A').
  3. Non-alphabetic characters are appended untouched.
  4. Join the list into a string.

Key concept: Modular arithmetic on character indices — subtracting a base, doing math mod 26, then adding the base back is the standard pattern for any letter-shift cipher.