Home >Backend Development >Python Tutorial >Conversion between bytes and string in python3
Preface
The most important new feature of Python 3 is probably a clearer distinction between text and binary data. Text is always Unicode and is represented by the str type, and 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 particularly clear. You cannot concatenate strings and byte packets, search for strings in byte packets (and vice versa), and pass strings into functions that take byte packets as parameters (and vice versa).
How to create bytes type data in python3.0
bytes([1,2,3,4,5,6,7,8,9]) bytes("python", 'ascii') # 字符串,编码
First set up an 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 = 'http://www.www.php.cn/' >>> type(website) <class 'str'> >>> website 'http://www.www.php.cn/' >>>
Encode according to utf-8 and convert to bytes
>>> website_bytes_utf8 = website.encode(encoding="utf-8") >>> type(website_bytes_utf8) <class 'bytes'> >>> website_bytes_utf8 b'http://www.www.php.cn/' >>>
Encode according to gb2312 and convert into bytes
>>> website_bytes_gb2312 = website.encode(encoding="gb2312") >>> type(website_bytes_gb2312) <class 'bytes'> >>> website_bytes_gb2312 b'http://www.php.cn/' >>>
Decode into string, not filled in by default
>>> website_string = website_bytes_utf8.decode() >>> type(website_string) <class 'str'> >>> website_string 'http://www.php.cn/' >>> >>>
Decode into string, using gb2312 method
>>> website_string_gb2312 = website_bytes_gb2312.decode("gb2312") >>> type(website_string_gb2312) <class 'str'> >>> website_string_gb2312 'http://www.php.cn/' >>>
For more articles related to the conversion between bytes and string in python3, please pay attention to the PHP Chinese website!