liveBook · Manning

Translation table

As explained in The Quick Python Book, Fourth Edition

A translation table is a mapping from source characters to replacement characters used for character-by-character text translation.

A translation table maps source characters to replacement characters for character-by-character text translation. Python's maketrans creates the table, and translate applies it across a string. section 6.4.5

The core rules are:

  • Pass two equally long strings to maketrans; the nth character in the first maps to the nth character in the second. section 6.4.5
  • Pass the resulting table to translate; each character found in the table is replaced with its mapped character. section 6.4.5
  • Supply empty first and second strings plus a third string to remove listed characters, such as punctuation. section 6.4.5
  • Create the table once before a loop rather than rebuilding it for every input line; repeated construction can reduce efficiency. section 6.10.2

Translate operators and brackets

For x = "~x ^ (y % z)", x.maketrans("~^()", "!&[]") followed by x.translate(table) produces "!x & [y % z]". A deletion table can instead remove characters such as "()~^%", producing "x y z".

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Explains table construction, indexed character mapping, application, deletion, and loop-efficiency trade-offs.
Examples
Demonstrates operator conversion, character deletion, and punctuation removal while cleaning a text file.
What it assumes
Assumes general programming and string knowledge while explaining maketrans and translate from their basic operations.
What you can do after
Apply it via Python string methods to replace or remove character sets without repeated replace calls.
How it connects
Connects maketrans and translate with string methods, the string module, replace, and text-file processing.

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 The Quick Python Book, Fourth Edition. The section links point to the parts of the book it draws on.