liveBook · Manning

Translation table

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

A translation table is a mapping that specifies replacement values for characters processed by a string translation operation.

A translation table maps characters to replacement values for str.translate(). str.maketrans() creates the table from a dictionary, while unmapped characters remain unchanged. section 4.4.3 section 8.1.2

A translation table supports these behaviors:

  • Replace every occurrence of a mapped character, such as digits in a phone number. section 4.4.3
  • Leave characters absent from the mapping untouched, preserving letters, spaces, and punctuation. section 8.1.2
  • Represent mappings using Unicode ordinals, strings, or None; None deletes the character. section 8.1.2

Translate a phone number

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

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

How deep it goes
Defines table creation and lookup behavior, including unchanged and deleted characters, but defers deeper explanation.
Examples
Demonstrates digit substitution in 867-5309 and Jenny = 867-5309 while preserving punctuation and letters.
What you can do after
Apply it via Python's str.maketrans() and str.translate() to replace or delete selected characters.
How it connects
Connects dictionaries, str.maketrans(), str.translate(), and Unicode ordinals.

Also explained in

Compare how 2 books explain translation table →

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.