Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีแปลง String เป็น Bytes ใน Python 3

ใช้เมธอด encode() ของ string class

ตัวอย่าง

>> s = u"HellΘ WΘrld"
>>> s.encode('utf-8')
b'Hell\xce\x98 W\xce\x98rld'

ค่า default encoding คือ 'utf-8' สามารถระบุ encoding อื่นได้ เช่น 'ascii', 'latin-1'