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 XYZOutput
def abc DEF ABCx, y and z wrap around to a, b and c.
Input 2
-1
HAL 9000Output
GZK 9000A 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 andtext.translate(table)applies it in one pass.
Show the explanation
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 % 26is-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 += chbuilds new strings over and over. - The explicit approach is also fine:
chr((ord(c) - base + s) % 26 + base)withbase = ord('a')orord('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.
