Algorithmscharacter range iteration

Character Range Iteration (Loops over a..z, 0..9, …)

TT
Testlaa Team
May 14, 20261 min read

Range iteration over characters often means looping consecutive ASCII letters or digits—either via ord/chr arithmetic or string.ascii_lowercase slices—without materializing huge strings.

Why this shows up in the real world

Seat labels AA, AB, AC increment like spreadsheet columns. Rotor ciphers step letters cyclically through the alphabet.

Core idea (explained for students)

Pattern: for k in range(ord('a'), ord('z') + 1): ch = chr(k). For cyclic shifts wrap with % 26 after subtracting base offset.

Try this in Python

import string


def shift_letter(ch: str, n: int) -> str:
    if ch not in string.ascii_lowercase:
        return ch
    base = ord("a")
    return chr((ord(ch) - base + n) % 26 + base)


print("".join(shift_letter(c, 3) for c in "abcxyz"))

Common mistakes

  • Forgetting inclusive/exclusive ends in range.
  • Mixing Unicode letters with ASCII-only arithmetic—accents break naive +1 loops.

Key takeaways

  • ASCII iteration pairs with Caesar cipher exercises.
  • Prefer string module constants for readability.

Tags:

StringsPythonStudents