The translate() function in python helps to replace some characters from the string with the characters specified in the given mapping table or dictionary. The mapping table can be created using the maketrans() method.
string.translate(table) #where table may be a dictionary or mapping table
The translate() function takes a single parameter. If we use a dictionary, we must use ASCII codes instead of characters.
Parameter | Description | Required / Optional |
---|---|---|
table | a table containing the mapping between two characters | Required |
The return value will be a string. If we are not specified the character in the dictionary/table, the character will not be replaced.
Input | Return Value |
---|---|
string | mapped string |
# define string
String1 = "abc"
String2 = "ghi"
String3 = "ab"
string = "abcdef"
print("Before Translation:", string)
mapping= string.maketrans(String1, String2, String3)
# translate string
print("After Translation:", string.translate(mapping))
Output:
Before Translation:abcdef After Translation:idef
# translation table
mapping = {97: None, 98: None, 99: 105}
string = "abcdef"
print("Before Translation:", string)
# translate string
print("After Translation:", string.translate(mapping))
Output:
Before Translation:abcdef After Translation:idef