str.translate() returns a new string by replacing characters according to a translation table. Build that table with str.maketrans(); characters without mappings remain unchanged. section 8.1.2 section 8.6
Encode digits in one pass
jumper = {'1': '9', '2': '8', '3': '7', '4': '6', '5': '0', '6': '4', '7': '3', '8': '2', '9': '1', '0': '5'} text = 'Jenny = 867-5309' print(text.translate(str.maketrans(jumper))) # Jenny = 243-0751 section 4.4.3 section 8.1.2
Use translate when every character should be transformed independently:
- Preserve punctuation and letters by mapping only the characters that need changing. section 4.4.3
- Prefer it over repeated str.replace() calls when substitutions can introduce characters that later replacements also target. section 4.4.4
- Map a character to None to delete it; translation tables can also map characters to replacement strings. section 8.1.2
>>> help(str.translate)
translate(self, table, /)
Replace each character in the string using the given translation table.
table
Translation table, which must be a mapping of Unicode ordinals to
Unicode ordinals, strings, or None.
The table must implement lookup/indexing via __getitem__, for instance a
dictionary or list. If this operation raises LookupError, the character is
left untouched. Characters mapped to None are deleted.
Inspect the method’s table requirements, lookup behavior, unchanged characters, and deletion rule. section 8.1.2

