1. 程式人生 > >30-python3 中 bytes 和 string 之間的互相轉換

30-python3 中 bytes 和 string 之間的互相轉換

轉自:http://www.jb51.net/article/105064.htm

 

password = b'123456'

等價於:

pw = '123456'
password = pw.encode(encoding='utf-8')

  

 

前言

Python 3 最重要的新特性大概要算是對文字和二進位制資料作了更為清晰的區分。文字總是 Unicode,由 str 型別表示,二進位制資料則由 bytes 型別表示。Python 3 不會以任意隱式的方式混用 str 和 bytes,正是這使得兩者的區分特別清晰。你不能拼接字串和位元組包,也無法在位元組包裡搜尋字串(反之亦然),也不能將字串傳入引數為位元組包的函式(反之亦然).

python3.0 中怎麼建立 bytes 型資料

  1.   >>> bytes([1,2,3,4,5,6,7,8,9])
  2.   >>> bytes("python", 'ascii') # 字串,編碼

 

首先來設定一個原始的字串,

  1.   >>> website = 'http://www.jb51.net/'
  2.   >>> type(website)
  3.   < class 'str'>
  4.   >>> website
  5.   'http://www.jb51.net/'

 

按 utf-8 的方式編碼,轉成 bytes

  1.   >>> website_bytes_utf8 = website.encode(encoding="utf-8")
  2.   >>> type(website_bytes_utf8)
  3.   < class 'bytes'>
  4.   >>> website_bytes_utf8
  5.   b'http://www.jb51.net/'

 

按 gb2312 的方式編碼,轉成 bytes

  1.   >>> website_bytes_gb2312 = website.encode(encoding="gb2312")
  2.   >>> type(website_bytes_gb2312)
  3.   < class 'bytes'>
  4.   >>> website_bytes_gb2312
  5.   b'http://www.jb51.net/'

 

解碼成 string,預設不填

  1.   >>> website_string = website_bytes_utf8.decode()
  2.   >>> type(website_string)
  3.   < class 'str'>
  4.   >>> website_string
  5.   'http://www.jb51.net/'

 

解碼成 string,使用 gb2312 的方式

  1.   >>> website_string_gb2312 = website_bytes_gb2312.decode("gb2312")
  2.   >>> type(website_string_gb2312)
  3.   < class 'str'>
  4.   >>> website_string_gb2312
  5.   'http://www.jb51.net/'