.translate()
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()
.
Syntax
The syntax of the .translate()
method is:
a_string.translate(table)
table
: a translation table that lists the pairings of two characters; often previously created by themaketrans()
method.- Returns a copy of the string in which each character has been mapped through the given translation table replacing or removing specified characters.
Example
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: abcdefTranslated string: 123def
Codebyte Example
The following example shows how to delete characters using a manual translation table:
All contributors
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python on Codecademy
- Skill path
Analyze Data with Python
Learn to analyze and visualize data using Python and statistics.Includes 8 CoursesWith CertificateIntermediate13 hours - Course
Learn Python 3
Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.With CertificateBeginner Friendly23 hours