Skip to Content
Modern Python Standard Library Cookbook
book

Modern Python Standard Library Cookbook

by Alessandro Molina
August 2018
Intermediate to advanced
366 pages
10h 14m
English
Packt Publishing
Content preview from Modern Python Standard Library Cookbook

How it works...

The core of this recipe is the usage of translation tables. Translation tables are mappings that link a character to its replacement. A translation table like {'c': 'A'} means that any 'c' must be replaced with an 'A'.

str.maketrans is the function used to build translation tables. Each character in the first argument will be mapped to the character in the same position in the second argument. Then all characters in the last argument will be mapped to None:

>>> str.maketrans('a', 'b', 'c')
{97: 98, 99: None}

The 97, 98, and 99 are the Unicode values for 'a', 'b', and 'c':

>>> print(ord('a'), ord('b'), ord('c'))
97 98 99

Then our mapping can be passed to str.translate to apply it on the target string. The interesting ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Advanced Python Development: Using Powerful Language Features in Real-World Applications

Advanced Python Development: Using Powerful Language Features in Real-World Applications

Matthew Wilkes

Publisher Resources

ISBN: 9781788830829Supplemental Content