Python maketrans()
Published Oct 18, 2023
Contribute to Docs
The maketrans() method is used for creating a translation table that can be used to perform character replacements or translations in strings. This method is particularly useful when there is a need to replace specific characters or substrings with other characters, or to remove certain characters from a string.
Syntax
string.maketrans(x,y,z)
x: A string containing characters to be replaced.y: A string containing characters with whichxneeds to be replaced.z: A string containing characters to be deleted.
The maketrans() method returns a translation table, which can then be used with the translate() method to perform the actual translations or replacements in a string.
Examples
This example shows the use of maketrans() method to replace characters in a string.
trans_table = str.maketrans('aeiou', '12345')str = "hello world"newstr = str.translate(trans_table)print(newstr)
This code will result in the following output:
h2ll4 w4rld
Codebyte Example
The following code is runnable and uses the maketrans() method.
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
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
- With Certificate
- Beginner Friendly.24 hours