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

來源:互聯網
上載者:User
前言

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') # 字串,編碼

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

Python 3.2.3 (default, Apr 11 2012, 07:15:24) [MSC v.1500 32 bit (Intel)] on win32Type "help", "copyright", "credits" or "license" for more information.>>> website = 'http://www.www.php.cn/'>>> type(website)<class 'str'>>>> website'http://www.www.php.cn/'>>>

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

>>> website_bytes_utf8 = website.encode(encoding="utf-8")>>> type(website_bytes_utf8)<class 'bytes'>>>> website_bytes_utf8b'http://www.www.php.cn/'>>>

按gb2312的方式編碼,轉成bytes

>>> website_bytes_gb2312 = website.encode(encoding="gb2312")>>> type(website_bytes_gb2312)<class 'bytes'>>>> website_bytes_gb2312b'http://www.php.cn/'>>>

解碼成string,預設不填

>>> website_string = website_bytes_utf8.decode()>>> type(website_string)<class 'str'>>>> website_string'http://www.php.cn/'>>>>>>

解碼成string,使用gb2312的方式

>>> website_string_gb2312 = website_bytes_gb2312.decode("gb2312")>>> type(website_string_gb2312)<class 'str'>>>> website_string_gb2312'http://www.php.cn/'>>>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.