Python String maketrans() - translate() Methods

17-01-23 Ahmed Obaid 949 0

​The maketrans() function returns a transposition table that transposes each character in the first string to the character in the second string at the same position.


How to formulate it like this:

maketrans(str1, str2, str3)

str1: Specifies the list of characters to replace.

str2: Specifies the list of characters that the characters should be replaced with.

str3: Specifies the list of characters to be deleted.

return value: Returns the permutation table specifying which permutations can be used by the translate() function.


Note: To apply the transpose table you created to any text, you must use the ()translate function.

Python String translate() Method


How to formulate it like this:

string. translate(table, delete)

string: The original string

table: The substitution table that defines which substitutions can be used.

delete: specifies the delete string as an optional argument.

return value: Returns a new string after permutations are made using the permutation table


In the following example we will use the translate() and maketrans() functions

Example:

# maketrans() and translate()
# specify to translate chars
str1 = "hm"
# specify to replace with
str2 = "xz"
# delete chars
str3 = "-"
# target string
string = "Ahmed-Obaid"
# using maketrans() to
table = string.maketrans(str1, str2, str3)
# Printing original string
print ("before: ", string)
# using translate() to make translations.
print ("after: ", string.translate(table))

 The output will be:3

before:  Ahmed-Obaid
after: AxzedObaid

 External sources:

 Built-in functions - official Python documentation

 If you have any questions or concerns, leave them in the comments



Tags


Python Python String string methods python python string translate and maketrans method

Share page