python3中bytes和string之间的互相转换

来源:互联网 发布:特价机票 知乎 编辑:程序博客网 时间:2024/05/16 05:52

Bytes objects are immutable sequences of single bytes. Since many major binary protocols are based on the ASCII text encoding, bytes objects offer several methods that are only valid when working with ASCII compatible data and are closely related to string objects in a variety of other ways
Strings implement all of the common sequence operations, along with the additional methods described below.
Strings also support two styles of string formatting, one providing a large degree of flexibility and customization (see str.format(), Format String Syntax and Custom String Formatting) and the other based on C printf style formatting that handles a narrower range of types and is slightly harder to use correctly, but is often faster for the cases it can handle (printf-style String Formatting).
The Text Processing Services section of the standard library covers a number of other modules that provide various text related utilities (including regular expression support in the re module).

  • Python3版本对文本和二进制数据作了更清晰的区分。文本是Unicode,由str类型表示,二进制数据则由bytes类型表示。Python3不会在任何地方混用str和bytes,这使得两者的区分特别清晰。所以不能拼接字符串和字节包,也无法在字节包里搜索字符串,也不能将字符串传入参数为字节包的函数.同样也不能在字符串中搜索字节包或者字节函数。

Python 3.6.2 (v3.6.2:5fd33b5, Jul 8 2017, 04:57:36) [MSC v.1900 64 bit (AMD64)] on win32
Type “help”, “copyright”, “credits” or “license” for more information.

python3.6中创建bytes型数据>>> bytes = bytes([1,2,3,4,5,6,7,8,9])>>> bstr = bytes("python", "ascii")
  • utf-8转换成bytes
>>> str = "It's all about inspiration">>> type(str)<class 'str'>>>> bstr = str.encode(encoding="utf-8")#其他字符编码就写其他类型的字符编码>>> type(bstr)<class 'bytes'>
  • bytes转换成str
>>> str = bstr.decode()#utf-8默认不填写,其他编码就填写参数decode("gb2312")>>> type(str)<class 'str'>
原创粉丝点击