Python String maketrans() Method (original) (raw)
Last Updated : 08 Jan, 2025
maketrans() method in Python is a powerful tool for creating mapping tables that specify how specific characters in a string should be replaced. This method is often used in conjunction with the translate() method to perform character replacements efficiently.
Let’s understand with help of an example:
Python `
Creating a translation table
t = str.maketrans("abc", "xyz")
Translating a string
res = "abcde".translate(t)
print(res)
`
Explanation:
- maketrans() method creates a mapping where a is replaced with x,
b
with y, and c with z. - translate() method applies this mapping to the string”abcde”, resulting in the transformed string “xyzde”.
Syntax of maketrans() Method
str.maketrans(x[, y[, z]])
Parameters
- **x: A string, dictionary, or sequence of characters that need to be replaced.
- y _(optional)_****:** A string with the same length as x, specifying the replacement characters.
- z _(optional)_****:** A string containing characters to be removed.
Return Type
- Returns a dictionary-like mapping table that can be passed to the translate() method.
Examples of maketrans() Method
1. Basic character mapping
Character mapping refers to associating one set of characters or symbols with another. Replacing vowels with corresponding uppercase letters.
Python `
Create a translation table
t = str.maketrans("aeiou", "AEIOU")
Translating a string
res = "Learn Python with GFG".translate(t)
print(res)
`
Output
LEArn PythOn wIth GFG
Explanation
- maketrans() maps lowercase vowels to their uppercase counterparts.
- translate() applies this mapping, transforming vowels in the string to uppercase.
2. Removing unwanted characters
Removing unwanted characters can be done by using regular expression or simple string operations in Python.
Python `
Create a translation table with characters to remove
t = str.maketrans("", "", ",.!?")
Translating a string
res = "Learn Python, with GFG!".translate(t)
print(res)
`
Output
Learn Python with GFG
Explanation
- maketrans() specifies characters to be removed using the third parameter.
- translate() eliminate these characters from the string.
3. Using a dictionary for mapping
This is useful if we need to replace specific words represented by their initial letters.
Python `
Create a translation table using a dictionary
t = str.maketrans({"L": "D", "w": "v"})
Translating a string
res = "Learn Python with GFG".translate(t)
print(res)
`
Output
Dearn Python vith GFG
Explanation
- The dictionary specifies the replacements.
- The mapping is applied directly to the string, replacing specified characters.