Python translate: replace characters without cascading replacements
Chained replacements can modify text inserted by an earlier replacement. A character translation table lets each original character select its replacement once.
Set up
Tested on Linux with CPython 3.12.14. Use Python 3.12 or later, Bash, a text editor, mktemp, rm and rmdir. The example needs no network access. Run the steps in the same terminal and stop if setup fails. Run Python without -O so the assertions stay enabled.
start_dir="$PWD"
work_dir="$(mktemp -d)" || exit 1
cd -- "$work_dir" || exit 1Run the example
Save this as translate_characters.py:
text = "ab-a!"
table = str.maketrans({"a": "b", "b": "c", "-": None, "!": "!!"})
translated = text.translate(table)
chained = text.replace("a", "b").replace("b", "c").replace("-", "").replace("!", "!!")
print("original:", text)
print("translated:", translated)
print("chained:", chained)
print("unmapped:", "a?".translate(table))
assert translated == "bcb!!"
assert chained == "ccc!!"
assert text == "ab-a!"Run:
python3 -B translate_characters.pyObserved output:
original: ab-a!
translated: bcb!!
chained: ccc!!
unmapped: b?Map original characters to their final replacement
The str.translate documentation allows each mapped character to become another character, a string, or nothing. Here None deletes the hyphen, and the two-character replacement expands the exclamation mark. Unmapped characters remain unchanged.
The inserted b is not translated again to c in the same call. The chained version does process that inserted character during its second call, so the results differ. Choose whichever behavior your transformation actually requires.
Limits
This is a character mapping, not a rule for replacing multi-character substrings. Mapping keys supplied as strings to str.maketrans must contain one character. Use a substring operation or a parser for rules about words or syntax. Translation also does not perform Unicode normalization; a visually combined character can consist of multiple code points. The original string remains unchanged.
Clean up
Remove the example file and the temporary directory:
rm -- translate_characters.py
cd -- "$start_dir" || exit 1
rmdir -- "$work_dir"
unset start_dir work_dirAcknowledgements
This post was created with assistance from AI.