1. 程式人生 > >python中 如何建立bytes、如何轉換str

python中 如何建立bytes、如何轉換str

Python3版本對文字和二進位制資料作了更清晰的區分。文字是Unicode,由str型別表示,二進位制資料則由bytes型別表示。Python3不會在任何地方混用str和bytes,這使得兩者的區分特別清晰。所以不能拼接字串和位元組包,也無法在位元組包裡搜尋字串,也不能將字串傳入引數為位元組包的函式.同樣也不能在字串中搜索位元組包或者位元組函式。

  1. 如何由其他型別建立bytes
>>> a = b'abc'
>>> type(a)
<class 'bytes'>
>>> b = bytes('abc','utf-8')
>>
> type(b) <class 'bytes'> >>> c= bytes([1,2,3,4,5,6,7,8,9]) >>> type(c) <class 'bytes'> >>> d = 'abc'.encode(encoding = "utf-8")#encoding也可以不填寫 >>> type(d) <class 'bytes'>
  1. bytes轉換成str
>>> str = d.decode()#utf-8預設不填寫,其他編碼就填寫引數decode("gb2312")
>>> type(str) <class 'str'>