+

Python | Maketrans () and translate () Functions

maketrans ()

The maketrans () function is used to build a transition table, i.e. specifies a list of characters to be replaced in the entire string, or characters to be removed from the string

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 needs to be deleted.

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

Translate with maketrans ()

For translating characters in a string, translate () is used to perform translations. This function uses the translation transform specified with maketrans ().

Syntax: translate (table, delstr)

Parameters:
table: Translate mapping specified to perform translations.
delstr: The delete string can be specified as optional argument is not mentioned in table.

Returns: Returns the argument string after performing the translations using the translation table.

Code no. 1: code for translation using translate () and maketrans ().

# Python3 demo code
# translations using
# maketrans () and translate ()

 
# uk Set for character translation

str1 = " wy "

  
# specify to replace with

str2 = "gf"

 
# remove characters

str3 = "u"

 
# target string

trg = "weeksyourweeks"

 
# using maketrans () for
# build translation
# table

tab le = trg.maketrans (str1, str2, str3)

 
# Print original line

print ( "The string before translating is:" , end = "")

print (trg)

  
# using translate () to translate.

print ( "The string after translating is: " , end = " ")

print (trg.translate (table))

Output:

 The string before translating is: weeksyourweeks The string after translating is: pythonengineering 

Translate without layouttrans ()

Translation can also be achieved by specifying the translation dictionary and passing as an object that acts as a display. In this case, there is no need for maketrans () to perform translations.

Code # 2: code for translation without layouttrans ().

# Python3 demo code
# no translations
# maketrans ( )

 
# display specification
# using ASCII

table = { 119 : 103 , 121 : 102 , 117 : None }

 
# target string

trg = "weeksyourweeks"

 
# Print original line

print ( "The string before translating is:" , end = " ")

print (trg)

  
# using translate () to translate.

print ( "The string after translating is:" , end = " ")

print (trg.translate (table))

Output:

 The string before translating is: weeksyourweeks The string after translating is: pythonengineering 

Application:
In many cases, errors can occur during coding or development, these functions provide simple and a quick way to replace and fix them and can potentially save you a lot of time.

Get Solution for free from DataCamp guru