Phương thức mã hóa chuỗi Python ()
Thí dụ
UTF-8 mã hóa chuỗi:
txt = "My name is Ståle"
x = txt.encode()
print(x)
Định nghĩa và Cách sử dụng
Phương encode()
thức mã hóa chuỗi, sử dụng mã hóa được chỉ định. Nếu không có mã hóa nào được chỉ định, UTF-8 sẽ được sử dụng.
Cú pháp
string.encode(encoding=encoding, errors=errors)
Giá trị tham số
Parameter | Description | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
encoding | Optional. A String specifying the encoding to use. Default is UTF-8 | ||||||||||||
errors | Optional. A String specifying the error method. Legal values are:
|
Các ví dụ khác
Thí dụ
Các ví dụ này sử dụng mã hóa ascii và một ký tự không thể mã hóa, hiển thị kết quả với các lỗi khác nhau:
txt = "My name is Ståle"
print(txt.encode(encoding="ascii",errors="backslashreplace"))
print(txt.encode(encoding="ascii",errors="ignore"))
print(txt.encode(encoding="ascii",errors="namereplace"))
print(txt.encode(encoding="ascii",errors="replace"))
print(txt.encode(encoding="ascii",errors="xmlcharrefreplace"))