A translation table maps characters to other characters. In Python we use the translate method to make many character replacements in strings.
We build a translation dictionary with str.maketrans()
and pass this to translate. This approach can be reused in many Python programs.
This example first uses str.maketrans
—this method receives 2 arguments. The first is the before and the second is the after.
str.maketrans
.# Make a translation table. # ... Map a to d, b to e, and c to f. dict = str.maketrans("abc", "def") print(dict) # Translate this value. value = "aabbcc" result = value.translate(dict) print(result){97: 100, 98: 101, 99: 102} ddeeff
Translate ignores characters that are not specified in the table. Keys
with values of None
are removed. With maketrans
, we specify "remove" characters as the third argument.
# Create translation table. table = str.maketrans("78", "12", "9") # Translate this string. input = "123456789" result = input.translate(table) # Write results. print(input) print(result)123456789 12345612
Rot13 rotates characters forward 13 places. It is reversible by applying the translation a second time. We write rot13
with maketrans
and translate.
rot13
against this translate version. And I found that translate is efficient. Please see the next section.# Create translation table. trans = str.maketrans("abcdefghijklmnopqrstuvwxyz", "nopqrstuvwxyzabcdefghijklm") # Apply rot13 translation. print("gandalf".translate(trans)) print("gandalf".translate(trans).translate(trans))tnaqnys gandalf
Next I tested the performance of translate. I tested the rot13
translation. I compared the version shown on this page (which uses translate) against a loop-based version.
1385003203.634 1385003203.885 translate method: 0.25 s 1385003205.569 rot13 method: 1.68 s
The maketrans
method does not need to be used. You can create a dictionary and store integer keys and values in it. You must use the integer representation (like 97).
ord
built-in converts a character to an integer. You can use ord
to construct the dictionary keys and values.None
to specify a character that should be removed. This is a special value in Python.The translate method in Python is straightforward—it translates characters to other characters. We removed characters and left others unchanged. And we benchmarked translate.