Conversion between bytes and string in python3, python3bytes
Preface
The most important new feature of Python 3 is to make a clearer distinction between text and binary data. The text is always Unicode, represented by the str type, and the binary data is represented by the bytes type. Python 3 does not mix str and bytes in any implicit way, which makes the distinction between the two very clear. You cannot concatenate strings and byte packets, search for strings in a byte packet (or vice versa), or input a string as a byte packet parameter (or vice versa ).
How to Create bytes data in python3.0
Bytes ([1, 2, 3, 4, 5, 6, 7, 8, 9]) bytes ("python", 'ascii ') # string, encoding
First, set an original string,
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.bkjia.com/'>>> type(website)<class 'str'>>>> website'http://www.bkjia.com/'>>>
Encoded in UTF-8 format and converted to bytes
>>> website_bytes_utf8 = website.encode(encoding="utf-8")>>> type(website_bytes_utf8)<class 'bytes'>>>> website_bytes_utf8b'http://www.bkjia.com/'>>>
Encoded in gb2312 format and converted to bytes
>>> website_bytes_gb2312 = website.encode(encoding="gb2312")>>> type(website_bytes_gb2312)<class 'bytes'>>>> website_bytes_gb2312b'http://www.bkjia.com/'>>>
Decodes data into a string. this parameter is left empty by default.
>>> website_string = website_bytes_utf8.decode()>>> type(website_string)<class 'str'>>>> website_string'http://www.bkjia.com/'>>>>>>
Decodes data into a string in gb2312 format.
>>> website_string_gb2312 = website_bytes_gb2312.decode("gb2312")>>> type(website_string_gb2312)<class 'str'>>>> website_string_gb2312'http://www.bkjia.com/'>>>
Summary
The above is all the content of this article. I hope the content of this article will help you in your study or work. If you have any questions, please leave a message, thank you for your support.