Hướng dẫn translate and maketrans python

❮ Phương thức chuỗi

Nội dung chính

  • Định nghĩa và Cách sử dụng
  • Giá trị tham số
  • Các ví dụ khác
  • String maketrans() Parameters
  • Return value from String maketrans()
  • Example 1: Translation table using a dictionary with maketrans()
  • Example 2: Translation table using two strings with maketrans()
  • Example 3: Translational table with removable string with maketrans()


Thí dụ

Tạo bảng ánh xạ và sử dụng nó trong translate()phương thức để thay thế bất kỳ ký tự "S" nào bằng ký tự "P":

txt = "Hello Sam!"
mytable = txt.maketrans("S", "P")
print(txt.translate(mytable))


Định nghĩa và Cách sử dụng

Phương maketrans()thức trả về một bảng ánh xạ có thể được sử dụng với phương thức để thay thế các ký tự đã chỉ định. translate()


Cú pháp

string.maketrans(x, y, z)

Giá trị tham số

ParameterDescription
x Required. If only one parameter is specified, this has to be a dictionary describing how to perform the replace. If two or more parameters are specified, this parameter has to be a string specifying the characters you want to replace.
y Optional. A string with the same length as parameter x. Each character in the first parameter will be replaced with the corresponding character in this string.
z Optional. A string describing which characters to remove from the original string.

Các ví dụ khác

Thí dụ

Sử dụng bảng ánh xạ để thay thế nhiều ký tự:

txt = "Hi Sam!"
x = "mSa"
y = "eJo"
mytable = txt.maketrans(x, y)
print(txt.translate(mytable))

Thí dụ

Tham số thứ ba trong bảng ánh xạ mô tả các ký tự mà bạn muốn xóa khỏi chuỗi:

txt = "Good night Sam!"
x = "mSa"
y = "eJo"
z = "odnght"
mytable = txt.maketrans(x, y, z)
print(txt.translate(mytable))

Thí dụ

Bản maketrans()thân phương thức này sẽ trả về một từ điển mô tả mỗi lần thay thế, bằng unicode:

txt = "Good night Sam!"
x = "mSa"
y = "eJo"
z = "odnght"
print(txt.maketrans(x, y, z))


❮ Phương thức chuỗi

In simple terms, maketrans() method is a static method that creates a one to one mapping of a character to its translation/replacement.

It creates a Unicode representation of each character for translation.

This translation mapping is then used for replacing a character to its mapped character when used in translate() method.


The syntax of maketrans() method is:

string.maketrans(x[, y[, z]])

Here, y and z are optional arguments.


String maketrans() Parameters

maketrans() method takes 3 parameters:

  • x - If only one argument is supplied, it must be a dictionary.
    The dictionary should contain a 1-to-1 mapping from a single character string to its translation OR a Unicode number (97 for 'a') to its translation.
  • y - If two arguments are passed, it must be two strings with equal length.
    Each character in the first string is a replacement to its corresponding index in the second string.
  • z - If three arguments are passed, each character in the third argument is mapped to None.

Return value from String maketrans()

The maketrans() method returns a translation table with a 1-to-1 mapping of a Unicode ordinal to its translation/replacement.


Example 1: Translation table using a dictionary with maketrans()

# example dictionary
dict = {"a": "123", "b": "456", "c": "789"}
string = "abc"
print(string.maketrans(dict))

# example dictionary
dict = {97: "123", 98: "456", 99: "789"}
string = "abc"
print(string.maketrans(dict))

Output

{97: '123', 98: '456', 99: '789'}
{97: '123', 98: '456', 99: '789'}

Here, a dictionary dict is defined. It contains a mapping of characters a,b and c to 123, 456, and 789 respectively.

maketrans() creates a mapping of the character's Unicode ordinal to its corresponding translation.

So, 97 ('a') is mapped to '123', 98 'b' to 456 and 99 'c' to 789. This can be demonstrated from the output of both dictionaries.

Also, if two or more characters are mapped in the dictionary, it raises an exception.


Example 2: Translation table using two strings with maketrans()

# first string
firstString = "abc"
secondString = "def"
string = "abc"
print(string.maketrans(firstString, secondString))

# example dictionary
firstString = "abc"
secondString = "defghi"
string = "abc"
print(string.maketrans(firstString, secondString))

Output

{97: 100, 98: 101, 99: 102}
ValueError: the first two maketrans arguments must have equal length

Here first, two strings of equal length abc and def are defined. And the corresponding translation is created.

Printing only the first translation gives you a 1-to-1 mapping to each character's Unicode ordinal in firstString to the same indexed character on secondString.

In this case, 97 ('a') is mapped to 100 ('d'), 98 ('b') to 101 ('e') and 99 ('c') to 102 ('f').

Trying to create a translation table for unequal length strings raises a ValueError exception indicating that the strings must have equal length.


Example 3: Translational table with removable string with maketrans()

# first string
firstString = "abc"
secondString = "def"
thirdString = "abd"
string = "abc"
print(string.maketrans(firstString, secondString, thirdString))

Output

{97: None, 98: None, 99: 102, 100: None}

Here, first, the mapping between the two strings firstString and secondString are created.

Then, the third argument thirdString resets the mapping of each character in it to None and also creates a new mapping for non-existent characters.

In this case, thirdString resets the mapping of 97 ('a') and 98 ('b') to None, and also creates a new mapping for 100 ('d') mapped to None.