Python Reference ยท String Methods
Python str.maketrans() and str.translate()
Reference for Python str.maketrans() and str.translate(): replace or delete many characters in one pass, the three call forms, mapping tables and common pitfalls.
str.translate() changes a string character by character using a translation table, and str.maketrans() builds that table. Together they replace, delete or swap many single characters in one pass, which is faster and cleaner than chaining several replace() calls.
A table is a dictionary that maps Unicode code points (integers) to replacement code points, replacement strings, or None to delete. maketrans() is a static method, so you call it on the class: str.maketrans(...).
table = str.maketrans("abc", "xyz") print("aabbcc".translate(table)) # xxyyzz
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
str.maketrans(x) str.maketrans(x, y) str.maketrans(x, y, z) str.translate(table)
| Name | Description |
|---|---|
x |
With one argument: a dictionary whose keys are single characters or code points, and whose values are code points, strings or None. With two or three arguments: a string of characters to replace. |
y |
A string of the same length as x; each character of x is replaced by the matching character of y. |
z |
A string of characters to delete. |
table |
For translate(): any object that supports table[code_point] and raises LookupError for unmapped characters. A dictionary from maketrans() is typical. |
Return value: maketrans() returns a dictionary keyed by code points. translate() returns a new string.
Raises: ValueError if x and y differ in length, or if a dictionary key is a string longer than one character. TypeError for arguments of the wrong type.
Usage notes
- One pass, character by character. Replacements are not reapplied to their own output, so
"ab".translate(str.maketrans("ab", "ba"))swaps cleanly, which chainedreplace()calls cannot do. - Single characters only. The keys of a table are single characters. To replace substrings, use
replace()orre.sub(). The values may be strings of any length. - Unmapped characters stay. If the table has no entry (or raises
LookupError), the character is copied unchanged. - Deleting. Map to
Noneor use the third argument ofmaketrans(). This is a quick way to strip punctuation:text.translate(str.maketrans("", "", string.punctuation)). - Build the table once. Creating it is the expensive part; create it at module level and reuse it.
- Last mapping wins. If the same character appears in
zandx, deletion overrides replacement. - Custom tables. Any object with
__getitem__works, like theShiftclass above, which is handy for computed mappings. - Bytes have
bytes.maketrans()andbytes.translate()working on 256-byte tables.
Related
str.replace(),str.lower(),str.strip(),ord(),chr()- Lessons: String methods, Strings