Python maketrans() Syntax

Syntax: maketrans(str1, str2, str3) 

Parameters: 

  • str1: Specifies the list of characters that need to be replaced. 
  • str2: Specifies the list of characters with which the characters need to be replaced. 
  • str3: Specifies the list of characters that need to be deleted.

Returns: Returns the translation table which specifies the conversions that can be used by translate()

Example:

In this code, we are demonstrating how to use str.translate() with a translation table created using string.maketrans() to modify a string by replacing and deleting specific characters.

Python3




# Python 3 Program to show working
# of translate() method
 
# First String
firstString = "gef"
 
# Second String
secondString = "eks"
 
# Third String
thirdString = "ge"
 
# Original String
string = "geeks"
print("Original string:", string)
 
translation = string.maketrans(firstString,
                               secondString,
                               thirdString)
 
# Translated String
print("Translated string:",
       string.translate(translation))


Output : 

Original string: geeks
Translated string: ks

Python String translate() Method

Python String translate() returns a string that is a modified string of givens string according to given translation mappings. 

Similar Reads

What is translate() in Python?

translate() is a built-in method in Python that is used to replace specific characters in a string with other characters or remove them altogether. The translate() method requires a translation table that maps the characters to be replaced to their replacements. This table can be generated using the maketrans() method, which takes two arguments: the characters to be replaced and their replacements....

Python String translate() Syntax

str.translate(translation_table)...

Python String translate() Examples

...

Python maketrans()

There are two ways to translate are:...

Python maketrans() Syntax

...

Use case of translate() and maketrans() Method

...