Skip to content
UniCircle
EasyCodingString methods

Shift letters with str.maketrans (Caesar shift)

Question PY-STR-104

Shift every English letter in the text forward by k places in the alphabet, wrapping from z back to a. Keep the case of each letter. Leave digits, spaces and punctuation unchanged. k may be negative (shift backwards) and may be larger than 26.

(This is a classic string exercise. A Caesar shift is not real encryption; anyone can reverse it by trying all 26 shifts.)

Constraints

  • −10^9 ≤ k ≤ 10^9
  • Text length ≤ 20000 characters

Input and output

Input
First line: k. The remaining lines are the text.
Output
The shifted text, with the same line breaks.

Examples

Input 1

3
abc xyz ABC XYZ

Output

def abc DEF ABC

x, y and z wrap around to a, b and c.

Input 2

-1
HAL 9000

Output

GZK 9000

A negative shift moves backwards: H becomes G. Digits stay the same.

Show hints
  • Reduce the shift first with k % 26. In Python the result is never negative.
  • str.maketrans(src, dst) builds a translation table and text.translate(table) applies it in one pass.
Show the explanation
Python
import string
s = k % 26                                   # Python's % is never negative for a positive divisor
lo, up = string.ascii_lowercase, string.ascii_uppercase
table = str.maketrans(lo + up, lo[s:] + lo[:s] + up[s:] + up[:s])
print(text.translate(table))

Why this is a good answer

  • `k % 26` handles negative and huge shifts in one step. In C or Java, -3 % 26 is -3, so there you would write ((k % 26) + 26) % 26. Mentioning that difference scores points.
  • Slicing lo[s:] + lo[:s] builds the rotated alphabet without arithmetic on every character.
  • `translate` makes one C-level pass over the string and leaves characters that are not in the table unchanged. A loop that does out += ch builds new strings over and over.
  • The explicit approach is also fine: chr((ord(c) - base + s) % 26 + base) with base = ord('a') or ord('A').

Security note: a shift cipher has only 26 keys, so trying all of them breaks it immediately. Real systems use vetted algorithms such as AES through a library. Never invent your own encryption.

Original UniCircle question. Last reviewed 22 Oct 2026.