str.translate()
Character-level transformation with a lookup table — build the table with str.maketrans, then apply in one linear pass.
Demo
The demo builds a table from your "from" and "to" strings (like str.maketrans("abc", "xyz")) — each character in "from" maps to the same-position character in "to". Characters not in "from" are passed through. Both strings must be the same length. Real code usually builds tables with str.maketrans, which also accepts a dict form and a "delete these chars" third argument.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| table | dict | yes | A mapping from Unicode ordinal (integer) to Unicode ordinal, string, or None. Characters not in the table are passed through unchanged. Almost always built via str.maketrans(). |
Return value
str — A copy of the string in which each character has been mapped through the given table. Keys are ORDINALS (integers, not characters); values may be integers, strings, or None (which deletes the character).
Common patterns
table = str.maketrans("abc", "xyz") result = text.translate(table)
clean = text.translate(str.maketrans("", "", "aeiou")) # remove vowels
import unicodedata def strip_accents(s): d = unicodedata.normalize("NFKD", s) return "".join(c for c in d if not unicodedata.combining(c))
text.translate({ord("&"): "and"})
Examples
Pitfalls
"hello".translate({"l": "L"})
"hello".translate(str.maketrans("l", "L"))
"abc".translate({ord("b"): ""})
"abc".translate({ord("b"): None})
str.maketrans("abc", "xy")
str.maketrans("abc", "xyz")
s = "hello" s.translate(str.maketrans("l", "L")) print(s)
s = s.translate(str.maketrans("l", "L"))
When to use
- Batch single-character substitutions in one linear pass
- Character deletion via the maketrans third argument
- Building a stripping / escaping / obfuscation table once and applying many times
- Any transformation that would otherwise chain many .replace() calls
- Multi-character substrings → str.replace or re.sub
- Case-insensitive replacement → normalize with casefold, then translate
- Regex-based transforms → re.sub with a callable
- Accent stripping via character mapping alone — combine with unicodedata
Notes
FAQ
For efficiency — internally CPython indexes the table by codepoint. Using integers keeps the lookup a plain integer indexing operation. In practice you never touch the ordinals directly; str.maketrans converts strings for you.