Home > Backend Development > Python Tutorial > Conversion between bytes and string in python3

Conversion between bytes and string in python3

高洛峰
Release: 2017-02-13 13:45:36
Original
1492 people have browsed it

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') # 字符串,编码
Copy after login

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 &#39;str&#39;>
>>> website
&#39;http://www.www.php.cn/&#39;
>>>
Copy after login

Encode according to utf-8 and convert to bytes

>>> website_bytes_utf8 = website.encode(encoding="utf-8")
>>> type(website_bytes_utf8)
<class &#39;bytes&#39;>
>>> website_bytes_utf8
b&#39;http://www.www.php.cn/&#39;
>>>
Copy after login

Encode according to gb2312 and convert into bytes

>>> website_bytes_gb2312 = website.encode(encoding="gb2312")
>>> type(website_bytes_gb2312)
<class &#39;bytes&#39;>
>>> website_bytes_gb2312
b&#39;http://www.php.cn/&#39;
>>>
Copy after login

Decode into string, not filled in by default

>>> website_string = website_bytes_utf8.decode()
>>> type(website_string)
<class &#39;str&#39;>
>>> website_string
&#39;http://www.php.cn/&#39;
>>>
>>>
Copy after login

Decode into string, using gb2312 method

>>> website_string_gb2312 = website_bytes_gb2312.decode("gb2312")
>>> type(website_string_gb2312)
<class &#39;str&#39;>
>>> website_string_gb2312
&#39;http://www.php.cn/&#39;
>>>
Copy after login

For more articles related to the conversion between bytes and string in python3, please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template