Sub topic 12
Mapping and Deleting Characters with translate
This chapter assumes you know basic Python syntax, string indexing, lists and tuples, and the replace and strip methods from earlier chapters. By the end you will build translation tables with str.maketrans and use translate to substitute or delete characters in a single pass.
Why translate exists
replace swaps one substring for another. To change many single characters, you would chain several replace calls, and each call scans the whole string again. translate takes a table that maps characters to replacements, and it applies the whole table in one scan.
Like every string method, translate returns a new string. The original is unchanged.
Building a table with maketrans
str.maketrans builds the table. It is called on the class str, not on a string instance. It has three forms.
- Two equal-length strings: each character in the first maps to the character at the same position in the second.
- Those two strings plus a third: every character in the third string is deleted.
- One dictionary: keys are characters (or code points) and values are replacement strings, code points, or
Nonefor deletion.
table = str.maketrans("abc", "xyz")
print("aabbcc".translate(table)) # xxyyzz
delete_vowels = str.maketrans("", "", "aeiou")
print("education".translate(delete_vowels)) # dctnIn the first example, a becomes x, b becomes y, and c becomes z. In the second, the two empty strings map nothing, and the third argument lists the characters to remove.
The dictionary form
The dictionary form is the only one that can replace a single character with several characters. The two-string form always maps one character to one character.
table = str.maketrans({"&": "and", "<": "(", ">": ")", "\t": None})
print("a & b\t<c>".translate(table)) # a and b(c)Keys must be single characters or integer code points. A key such as "ab" raises ValueError. A value of None deletes the character.
How the table works internally
maketrans returns a dictionary that maps Unicode code points (integers) to replacements. You can inspect it.
table = str.maketrans("ab", "xy")
print(table) # {97: 120, 98: 121}
print("cab".translate(table)) # cxytranslate looks up each character's code point in the table. If the code point is missing, the character is kept as it is. This means you can also pass a hand-built dictionary of integer keys straight to translate.
A practical use: removing punctuation
The standard library's string.punctuation holds the ASCII punctuation characters. Combined with translate, it gives a short cleanup step.
import string
remove_punct = str.maketrans("", "", string.punctuation)
text = "Hello, World! It's 5 o'clock."
print(text.translate(remove_punct)) # Hello World Its 5 oclockCommon errors
- Passing strings of different lengths to the two-string form raises
ValueError. - Calling
translatewith a plain dictionary of one-character string keys does nothing, becausetranslatelooks up integer code points. Build the table withstr.maketransto convert them. - Expecting
translateto match multi-character sequences. It works one character at a time, so usereplaceorrefor sequences such as"ab". - Forgetting to assign the result. The original string stays as it was.
Choosing between replace and translate
| Task | Better tool |
|---|---|
| Replace one substring with another | `replace` |
| Replace a limited number of occurrences | `replace` with a count |
| Map many single characters at once | `translate` |
| Delete a set of characters | `translate` |
| Match patterns or sequences | `re` module |
Exercise
Write code that removes all digits from the string "a1b22c333" using translate and maketrans. What does it print, and why does it not change the original variable?
Show answer
Use string.digits as the deletion argument:
import string
s = "a1b22c333"
table = str.maketrans("", "", string.digits)
print(s.translate(table)) # abc
It prints abc. Strings are immutable, so translate returns a new string, and s still holds "a1b22c333" unless you assign the result back to it.
Exercise
Using the dictionary form of str.maketrans, how would you turn "<b>" into "[b]" and replace each "&" with "and"?
Show answer
table = str.maketrans({"<": "[", ">": "]", "&": "and"}); then "<b> & <i>".translate(table) gives "[b] and [i]". The dictionary form is needed because "&" maps to a three-character string.