Python3 笔记:字符串的 encode() 和 bytes.decode()

1、encode() 方法以指定的编码格式编码字符串。

语法:str.encode(encoding='UTF-8',errors='strict')

参数:

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

errors:设置不同错误的处理方案。默认为 'strict',意为编码错误引起一个UnicodeError。 其他可能的值有 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' 以及通过 codecs.register_error() 注册的任何值。

该方法返回编码后的字符串,它是一个 bytes 对象。

python 复制代码
str1 = '字符串'
str2 = str1.encode("UTF-8")
str3 = 'hello'
str4 = str3.encode("UTF-8")
print(str2)	# 运行结果:b'\xe5\xad\x97\xe7\xac\xa6\xe4\xb8\xb2'
print(str4)	# 运行结果:b'hello'

2、decode() 方法以指定的编码格式解码 bytes 对象。默认编码为 'utf-8'。

语法:bytes.decode(encoding="utf-8", errors="strict")

encoding -- 要使用的编码,如"UTF-8"。

参数:

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

errors:设置不同错误的处理方案。默认为 'strict',意为编码错误引起一个UnicodeError。 其他可能得值有 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' 以及通过 codecs.register_error() 注册的任何值。

Python3 中没有 decode 方法,但我们可以使用 bytes 对象的 decode() 方法来解码给定的 bytes 对象,这个 bytes 对象可以由 str.encode() 来编码返回。

python 复制代码
str1 = '字符串'
str2 = str1.encode("UTF-8")
print(str2)	# 运行结果:b'\xe5\xad\x97\xe7\xac\xa6\xe4\xb8\xb2'

str3 = str2.decode('UTF-8','strict')
print(str3)	# 运行结果:字符串
相关推荐
智航GIS7 分钟前
2.3 运算符详解
开发语言·python
屋顶那猫7 分钟前
使用pyinstaller打包pytest项目
python·pytest
web3.088899911 分钟前
接入API-自动化批量获取淘宝商品详情数据
开发语言·python
刹那间的回眸x.y17 分钟前
UnitTestReport挺好用
python
码农水水41 分钟前
腾讯Java面试被问:阻塞队列BlockingQueue的实现原理
java·后端·python·面试
曲幽43 分钟前
Flask登录验证实战:从零构建一个基础的账号密码登录系统
python·flask·web·session·username·login
love530love1 小时前
【笔记】Intel oneAPI 开发环境配置
人工智能·windows·笔记·oneapi·onednn·deep neural
HansenPole8251 小时前
元编程笔记
笔记·网络协议·rpc
superman超哥1 小时前
仓颉类型别名的使用方法深度解析
c语言·开发语言·c++·python·仓颉
charlie1145141911 小时前
Git团队协作完全入门指南(上)
笔记·git·学习·教程·工程