Python String maketrans() Method
Last Updated :
05 Oct, 2021
Python String maketrans() function is used to construct the transition table i.e specify the list of characters that need to be replaced in the whole string or the characters that need to be deleted 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 need to be deleted.
Returns:
Returns the translation table which specifies the conversions that can be used by translate()
Translate Using maketrans()
To translate the characters in the string translate() is used to make the translations. This function uses the translation mapping specified using the 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.
Example: Code to translate using translate() and maketrans()
Python3
str1 = "wy"
str2 = "gf"
str3 = "u"
trg = "weeksyourweeks"
table = trg.maketrans(str1, str2, str3)
print ( "The string before translating is : " , end = "")
print (trg)
print ( "The string after translating is : " , end = "")
print (trg.translate(table))
|
Output:
The string before translating is : weeksyourweeks
The string after translating is : geeksforgeeks
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...