Translate String Python

Several characters in a Python string may need different changes before the text is used elsewhere. str.translate() applies a table of character rules and returns a new string.

This article shows how to build that table with str.maketrans() and when a character table fits better than replace().

TL;DR: Use str.translate() for character maps

Build a table with str.maketrans(), then pass it to the string’s translate() method to map, expand or delete selected characters.

  • Use a dictionary when replacements vary in length or include deletions.
  • Use two equal-length strings for one-to-one character swaps.
  • Use replace() for a known substring rather than a character table.

What is str.translate() in Python?

The method returns a new string after applying the table to each character. A mapping to None removes that character.

The companion str.maketrans builds a table accepted by translate. Dictionary values can be an ordinal, replacement text, or None.

Terminal output of a Python string translation example

In my python3 translate_demo.py run, the program translated separators, removed selected characters and expanded one mapping. The output was:

one two three
ab
XYXYXY

The final line shows that one source character can map to several output characters.

How to translate a Python string step by step

Create the mapping that matches the task, then apply it to the source string.

Step 1: Define the characters to change

Provide equal-length strings for position-by-position substitutions. The example swaps each character in the pair.

table = str.maketrans("ab", "ba")
print("aabb".translate(table))

The output from python3 translate_compare.py includes:

ba
aa

The first line is the table-based swap. The second comes from chained replacements.

The comparison script gives a useful distinction when replacement values overlap with source characters. Its output is:

Terminal comparison of translate and chained replace output
ba
aa

The chained calls run sequentially. The second replacement sees letters inserted by the first.

Step 2: Add deletion or longer replacements

The dictionary below combines replacement, expansion and deletion.

table = str.maketrans({"-": " ", "x": "ks", "7": None})
value = "x-ray 7"
print(value.translate(table))

This table changes hyphens to spaces, expands x, and removes every 7.

Step 3: Apply the table to the input

Call the method on the string and assign its return value when later code should use the transformed text.

import string

text = "Order-7: x-ray"
table = str.maketrans("-", " ", string.digits)
translated = text.translate(table)
print(translated)

The third argument marks every digit for deletion. Use this form when the substitutions are one-to-one and deletion applies to a set of characters.

A lookup uses a Unicode code point, the integer assigned to a character. A dictionary can use a character key such as “é” or its integer ordinal. str.maketrans converts character keys to ordinal keys in the returned table.

Use the ordinal function when the mapping is generated from numeric data. For a short fixed mapping, character keys are concise.

A mapping can expand one selected symbol into a chosen text sequence, as the example output demonstrates. It does not infer pronunciation or translate a sentence.

Decide whether uppercase and lowercase variants need separate entries.

A data import may use several separators that should become spaces, while a marker character should be removed.

A dictionary can express both actions in one table. When unwanted characters form a fixed set and substitutions are position-based, the third argument of str.maketrans() keeps deletion separate from paired replacements.

The standard library punctuation constant contains ASCII marks, not every Unicode punctuation mark. Only listed entries are affected.

The standard library digit constant covers ASCII digits from zero through nine.

String translation does not combine or standardize visually similar Unicode sequences. A letter may be represented by one code point or by a base character followed by a combining mark.

If equality must treat canonically equivalent text the same way, normalize it before mapping. Choose a form that fits the application and preserve the original when its representation carries meaning.

For a known multi-character token, use the substring replacement method because the token can span several characters.

A regular expression fits selection by class or boundary. Choose among character rules, exact substrings and matching conditions based on the input.

Test a table with one intended mapping, one deletion and one unlisted character.

When a mapping is assembled from external configuration, validate its keys and values at the boundary where that data enters the program. A typo in a key can pass silently because unmapped input characters remain unchanged. That behavior is useful for partial tables, but it also means a misspelled key may look like a successful run while leaving the target character untouched.

If the same input is translated twice with the same table, the second call applies the rules to the first result. Apply a transformation twice only when the mapping is intended to be repeatable.

Edge cases when translating Python strings

The table-building signatures have specific constraints. I ran an unequal-length mapping to check the failure a newcomer may encounter.

str.maketrans("AB", "a")

Python returned the ValueError stating that the first two maketrans arguments must have equal length. Match their lengths to fix it.

CaseSymptomFix
Unequal mapping stringsValueError from str.maketrans()Make their lengths equal or use a dictionary.
Python 2-era callOld examples pass multiple arguments to text translate()In Python 3, build a table with str.maketrans() and pass that single table.
Only edge characters should goA translation table removes matching characters everywhereChoose strip() for a set at string edges or removeprefix() for one exact prefix.

Python 3’s text-string API takes one table. The separate bytes translation method operates on bytes. The Python standard library documents both methods.

For Unicode normalization behavior, consult the standard library documentation linked below.

Conclusion

Use a character table when it expresses the rule more clearly than chained replacements. The examples above show which table form fits each job.

The official references explain str.maketrans() and str.translate(). AskPython’s guide to removing characters from a string covers a related cleanup task. Its walkthrough on splitting a string is useful when the intended operation is to separate tokens rather than transform individual characters.

FAQ

These answers address common questions about Python string translation tables.

How do I replace multiple characters in a Python string?

Build a table with str.maketrans() and pass it to the string’s translate() method. Use a dictionary for mixed replacements or deletions.

Does str.translate() translate a sentence into another language?

No. It maps individual characters according to a table. Natural-language translation requires a separate translation tool or service.

Vijaykrishna Ram
Vijaykrishna Ram
Articles: 99