วิธี encode() ของ Python ตัวอักษร
ตัวอย่าง
เข้ารหัสตัวอักษรใน UTF-8:
txt = "My name is Ståle" x = txt.encode() print(x)
คำหมายและวิธีใช้
วิธี encode() ใช้รหัสการเข้ารหัสที่กำหนดสำหรับตัวอักษร ถ้าไม่กำหนดรหัสการเข้ารหัส จะใช้ UTF-8
วิธีการใช้
string.encode(encoding=encoding, errors=errors)
ค่าปรากฏการณ์
ปรากฏการณ์ | คำอธิบาย |
---|---|
encoding | ตัวเลือกตามความต้องการ สตริง กำหนดรหัสการเข้ารหัสที่ใช้ ค่าเริ่มต้นคือ UTF-8 |
errors |
ตัวเลือกตามความต้องการ สตริง กำหนดวิธีการที่ผิดพลาด ค่าที่ถูกต้องคือ:
|
ตัวอย่างเพิ่มเติม
ตัวอย่าง
ตัวอย่างนี้ใช้การเข้ารหัส ascii และอักษรที่ไม่สามารถเข้ารหัสได้ เพื่อแสดงผลที่มีความผิดพลาดต่าง ๆ
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")) print(txt.encode(encoding="ascii",errors="strict"))