translate() goes through a string one character at a time and uses a translation table to decide what to do with each one: replace it, delete it, or leave it alone. Characters that are not in the table are copied unchanged.
The table is almost always built with maketrans(). It is the best tool when you want to change many single characters in one pass, for example to remove all punctuation. The method returns a new string.
text.translate() is a method of the built-in str type: call it on a string with dot notation. No import is needed, and it never changes the original string.
Syntax
Pass a translation table. It is required.
python
result = text.translate(table)
Call
What it does
"hello".translate(str.maketrans("el", "ip"))
Returns 'hippo'. Each e becomes i, and each l becomes p.
"a-b".translate({ord("-"): None})
Returns 'ab'. A value of None deletes the character.
"a b".translate({ord(" "): "__"})
Returns 'a__b'. A value can be a string of any length.
To replace one fixed piece of text use replace(). To build a table, use maketrans(). To remove only the ends of a string, use strip().
Library declarations
python
str.translate(table) -> str
# returns: a new string with the table applied
# table: a dict or any object that supports lookup by code number
Parameters
Parameter
Description
table
Required. A dictionary, usually made by str.maketrans(), whose keys are Unicode code numbers. Its values are replacement strings, code numbers, or None to delete.
Return Value
Return Value
Description
str
A new string with the table applied. Characters that are not in the table are kept. The original string is not changed.
Python Examples
Example 1 — Replace Vowels With Numbers
Build a table with maketrans() and use it on two words.