Interconversion between bytes and string in python3

  • 2020-05-24 05:48:39
  • OfStack

preface

Perhaps the most important new feature of Python 3 is a clearer distinction between text and binary data. Text is always Unicode, represented by type str, and base 2 data by type bytes. Python 3 does not mix str and bytes in any implicit way, which makes the distinction particularly clear. You cannot concatenate strings and byte packets, nor can you search for strings in byte packets (and vice versa), nor can you pass a string into a function that takes a byte packet (and vice versa).

How do you create bytes data in python 3.0


bytes([1,2,3,4,5,6,7,8,9])
bytes("python", 'ascii') #  String, encoding 

I'm going to set the original string,


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

Code as utf-8 and convert to bytes


>>> website_bytes_utf8 = website.encode(encoding="utf-8")
>>> type(website_bytes_utf8)
<class 'bytes'>
>>> website_bytes_utf8
b'https://www.ofstack.com/'
>>>

Code as gb2312 and convert to bytes


>>> website_bytes_gb2312 = website.encode(encoding="gb2312")
>>> type(website_bytes_gb2312)
<class 'bytes'>
>>> website_bytes_gb2312
b'https://www.ofstack.com/'
>>>

Decode to string, default not filled


>>> website_string = website_bytes_utf8.decode()
>>> type(website_string)
<class 'str'>
>>> website_string
'https://www.ofstack.com/'
>>>
>>>

Decode it into string, using gb2312


>>> website_string_gb2312 = website_bytes_gb2312.decode("gb2312")
>>> type(website_string_gb2312)
<class 'str'>
>>> website_string_gb2312
'https://www.ofstack.com/'
>>>

conclusion


Related articles: