轉自:http://www.jb51.net/article/105064.htm
前言
Python 3 最重要的新特性大概要算是對文本和二進制數據作了更為清晰的區分。
文本總是 Unicode,由 str 類型表示,二進制數據則由 bytes 類型表示。
Python 3 不會以任意隱式的方式混用 str 和 bytes,正是這使得兩者的區分特別清晰。
你不能拼接字符串和字節包,也無法在字節包里搜索字符串(反之亦然),也不能將字符串傳入參數為字節包的函數(反之亦然).
python3.0 中怎么創建 bytes 型數據
>>> bytes([1,2,3,4,5,6,7,8,9])
>>> bytes("python", 'ascii') # 字符串,編碼
字符串
>>> website = 'http://www.jb51.net/'
>>> type(website)
<class 'str'>
>>> website
'http://www.jb51.net/'
utf-8 轉bytes
>>> website_bytes_utf8 = website.encode(encoding="utf-8")
>>> type(website_bytes_utf8)
<class 'bytes'>
>>> website_bytes_utf8
b'http://www.jb51.net/'
解碼成 string,默認不填
>>> website_string = website_bytes_utf8.decode()
>>> type(website_string)
<class 'str'>
>>> website_string
'http://www.jb51.net/'