liveBook · Manning

Translate

As explained in Tiny Python Projects: Learn coding and testing with puzzles and games

str.translate() is a Python string method that returns a new string by mapping characters according to a translation table.

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

How Tiny Python Projects: Learn coding and testing with puzzles and games covers it

How deep it goes
Defines translation tables, Unicode ordinal mappings, replacement strings, deletion with None, and lookup behavior.
Examples
Demonstrates encoding phone-like digit strings while leaving letters, spaces, hyphens, and equals signs unchanged.
What it assumes
Assumes familiarity with strings and dictionaries while demonstrating table construction from a character-mapping dictionary.
What you can do after
Apply it via str.maketrans() and str.translate() to build reusable character-substitution transformations.
How it connects
Connects string immutability, str.maketrans(), str.replace(), dictionaries, and list comprehensions.

Also explained in

Compare how 2 books explain translate →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Tiny Python Projects: Learn coding and testing with puzzles and games. The section links point to the parts of the book it draws on.