How to explain the str.maketrans function in Python 3.6?

str.maketrans builds a translation table, which is a mapping of integers or characters to integers, strings, or None. Think of it like a dictionary where the keys represent characters in the input string and the values they map to represent characters in the output string.

We go through the string to translate and replace everything that appears as a key in the mapping with whatever its value in the map is, or remove it if that value is None.

You can build a translation table with one, two, or three arguments (I think this may be what’s confusing you). With one argument:

str.maketrans({'a': 'b', 'c': None})

You give the function a mapping that follows the rules for translation tables and it returns an equivalent table for that mapping. Things that map to None are removed

With two arguments:

str.maketrans('abc', 'xyz')

You give it two strings. Each character in the first string is replaced by the character at that index in the second string. So 'a' maps to 'x', 'b' to 'y', and 'c' to 'z'.

The one you’re using, with three arguments, works the same as two arguments, but has a third string.

str.maketrans('abc', 'xyz', 'hij')

This is the same as the two argument version, except that the characters from the third string are removed, as if they were mapped to None. So your table is saying “Don’t replace anything, but remove the characters that show up in this string”.

Leave a Comment