python bytes与str转换

概述

在python中,str(字符串)在内存中是Unicode编码,是以字符为单位的,一个字符对应若干个字节

bytes是以字节为单位的

str与bytes可以互相转换

什么时候需要str转换成bytes

而在网络上传输,或者保存到磁盘上,是以 字节 为单位操作的,此时就需要把 字符串 转换成 字节

str与bytes互相转换

str转bytes,用encode()编码
bytes转str,用decode()解码

str转换成bytes

方法1

通过str的encode()方法实现,说明见链接:
http://www.runoob.com/python/att-string-encode.html

s='你好,Python'
#用UTF-8编码格式
b=s.encode('utf-8')
print(b)

结果如下:

b'\xe4\xbd\xa0\xe5\xa5\xbd\xef\xbc\x8cPython'

\x表示16进制

方法2:

使用bytes()实现

s='你好,Python'
#用UTF-8编码格式
b=bytes(s,'utf-8')
print(b)

bytes转换成str

通过bytes的decode()方法实现

语法:

#用UTF-8编码格式
decode(encoding='UTF-8',errors='strict')

参数:

  • encoding : 要使用的编码,如”UTF-8”。

  • errors : 有些字符无法转换时,设置不同错误的处理方案。

    • ‘strict’,默认值,意为编码错误引起一个UnicodeError。
    • ‘ignore’:忽略非法字符
    • ‘replace’:用?取代非法字符
    • ‘xmlcharrefreplace’:用XML的字符引用替换不支持的字符(仅在写入文件时支持)
    • ‘backslashreplace’:用Python的反向转义序列替换格式错误的数据

以及通过 codecs.register_error() 注册的任何值。

返回值:
  • 该方法返回解码后的字符串。

例子:

b=b'\xe4\xbd\xa0\xe5\xa5\xbd\xef\xbc\x8cPython'
s2=b.decode('utf-8')
print(s2)

显示结果如下:

你好,Python

感谢:
https://www.cnblogs.com/654321cc/p/7419124.html
https://cloud.tencent.com/developer/ask/187671


原文出处:/show_1EF4e2yG4zxA.html