Hướng dẫn translate and maketrans python
❮ Phương thức chuỗi Show
Nội dung chính
Thí dụTạo
bảng ánh xạ và sử dụng nó trong txt = "Hello Sam!" Định nghĩa và Cách sử dụngPhương Cú phápstring.maketrans(x, y, z) Giá trị tham số
Các ví dụ khácThí dụSử dụng bảng ánh xạ để thay thế nhiều ký tự: txt = "Hi Sam!" 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!" Thí dụBản txt = "Good night Sam!" ❮ Phương thức chuỗi In simple terms, 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 string.maketrans(x[, y[, z]]) Here, y and z are optional arguments. String maketrans() Parameters
Return value from String maketrans()The Example 1: Translation table using a dictionary with maketrans()
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.
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()
Output {97: 100, 98: 101, 99: 102} ValueError: the first two maketrans arguments must have equal length Here first, two strings of equal length 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 Example 3: Translational table with removable string with maketrans()
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 In this case, thirdString resets the mapping of 97 ('a') and 98 ('b') to |