Anonymous contributor's avatar
Anonymous contributor
Anonymous contributor's avatar
Anonymous contributor
Published Oct 6, 2023
Contribute to Docs

The .translate() method takes a translation table as an argument and maps the ordinal of a character to its corresponding replacement or deletion. A translation table can be created using the static method maketrans().


The syntax of the .translate() method is:

  • table: a translation table that lists the pairings of two characters; often previously created by the maketrans() method.
  • Returns a copy of the string in which each character has been mapped through the given translation table replacing or removing specified characters.


The following example shows custom character mapping using a translation table and .translate():

original_string = "abcdef"
print("Original string:", original_string)
translation_table = str.maketrans('abc', '123')
# translates original_string by mapping 'a' to '1', 'b' to '2', and 'c' to '3'
translated_string = original_string.translate(translation_table)
print("Translated string:", translated_string)

This example outputs the following:

Original string: abcdef
Translated string: 123def

Codebyte Example

The following example shows how to delete characters using a manual translation table:

Visit us
Hide code
Hide output
Hide output

All contributors

Looking to contribute?

Learn Python on Codecademy