Algorithmscharacter replacement

Character Replacement (Substitutions and Transliteration)

TT
Testlaa Team
May 14, 20261 min read

Replacement swaps characters according to a table—str.translate with maketrans, simple loops, or regex subs. It powers ciphers, slugification, and typo fixes.

Why this shows up in the real world

Keyboard layout converters remap keys. Profanity filters swap letters for safe symbols. License plate OCR replaces O→0 when context demands.

Core idea (explained for students)

table = str.maketrans('ABC', '123'); s.translate(table). For conditional replacements, sometimes build a list comprehension easier to read than chained replaces.

Try this in Python

def rot13(s: str) -> str:
    import codecs

    return codecs.encode(s, "rot_13")


print(rot13("Hello"))

Common mistakes

  • Overlapping replacements with chained replace—order matters.
  • translate deleting characters when mapping to None—powerful but easy to misuse.

Key takeaways

  • Prefer one translation table over many sequential replaces for performance and clarity.

Tags:

StringsPythonStudents