C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Then: We call the translate method. We pass the dictionary argument returned by str.maketrans.
Info: Internally translate replaces all the "before" characters to "after" characters. We print some of the variables.
Tip: The table used by translate stores integers. The letter "a" is mapped to 97. This is the ASCII value of "a."
Python program that uses maketrans, translate
# 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)
Output
{97: 100, 98: 101, 99: 102}
ddeeff
Here: We change the characters 7 and 8. We remove the character 9. And the translate method ignores all others.
Python program that ignores, removes characters
# Create translation table.
table = str.maketrans("78", "12", "9")
# Translate this string.
input = "123456789"
result = input.translate(table)
# Write results.
print(input)
print(result)
Output
123456789
12345612
Note: Due to sheer, crushing boredom I benchmarked a loop-based rot13 against this translate version.
And: My boredom was alleviated when I found that translate is efficient. Please see the next section.
Python program that applies rot13 translation
# Create translation table.
trans = str.maketrans("abcdefghijklmnopqrstuvwxyz",
"nopqrstuvwxyzabcdefghijklm")
# Apply rot13 translation.
print("gandalf".translate(trans))
print("gandalf".translate(trans).translate(trans))
Output
tnaqnys
gandalf
Thus: I advise using translate instead of other approaches, like testing each character in a loop, for most Python requirements.
Benchmark results: Python
1385003203.634
1385003203.885 translate method: 0.25 s
1385003205.569 rot13 method: 1.68 s
Ord: The ord built-in converts a character to an integer. You can use ord to construct the dictionary keys and values.
None: Also, please use the value None to specify a character that should be removed. This is a special value in Python.
NoneReview: We used translate with characters. We removed characters and left others unchanged. And we benchmarked translate.