2025, Sep 16 17:00

Python str.maketrans and str.translate explained: numeric codes and character-to-character mapping

Learn why Python str.maketrans returns numeric codes and how to build a character-to-character mapping, or create dict(zip) pairs, for clear translation tables.

Why str.maketrans shows numeric codes and how to build a symbol-to-symbol table

When you build a translation table in Python from two strings, it’s easy to be surprised by the result. Instead of a neat mapping from characters to characters, you see a dictionary full of numeric values. The question is simple: why does it work this way, and how do you get a character-based table if that’s what you need?

Example

source_seq = 'abcd'
target_seq = 'dcba'
map_table = str.maketrans(source_seq, target_seq)
print(map_table)

What’s going on and why

The behavior is intentional. The API is designed for use with str.translate, and the translation table it returns carries mappings as numeric symbol codes. That format is exactly what translate expects, which is why you see numbers instead of the symbols themselves.

How to get a symbol-based mapping

If your goal is a human-readable or symbol-to-symbol dictionary built from variables, you can map the numeric keys and values back to characters. One way is to convert both sides into characters. Another way is to construct the mapping directly from the source and target strings.

# Convert numeric codes back to characters
char_map = {chr(k): chr(v) for k, v in map_table.items()}
print(char_map)

# Or build directly from the input strings
pair_map = dict(zip(source_seq, target_seq))
print(pair_map)

Both approaches yield the same mapping in terms of characters: {'a': 'd', 'b': 'c', 'c': 'b', 'd': 'a'}.

Why this matters

Understanding that the translation table is intended for str.translate explains the numeric representation and eliminates the confusion when inspecting it. When you do need a symbol-level view—for example, to display the mapping, to log it, or to derive it from variables—you can convert the numeric entries back to characters or construct the dictionary directly from the original strings.

Takeaways

str.maketrans returns a structure that aligns with str.translate, hence the numeric codes. If you want a character-to-character table derived from variables, either convert the table’s keys and values to characters or create the mapping straight from the input strings using dict(zip(...)). Keeping both representations in your toolbox makes it straightforward to use the API as intended and, when necessary, to present the mapping in a more readable form.

The article is based on a question from StackOverflow by Will Ronson and an answer by Julien.