Phương thức chuỗi maketrans () trong Python
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ố
Parameter | Description |
---|---|
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))