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)	# 运行结果:字符串
相关推荐
星星20259 分钟前
电子电气架构全解析
笔记
智者知已应修善业44 分钟前
【给定英文字符串统计最多小写最前输出】2023-2-27
c语言·开发语言·c++·经验分享·笔记·算法
咕白m6251 小时前
通过 Python 在 PDF 中添加页面
python
wa的一声哭了1 小时前
Linux服务器配置ssh免密登陆多台服务器、服务器别名配置
linux·运维·服务器·网络·arm开发·python·ssh
我的golang之路果然有问题1 小时前
mac配置 unity+vscode的坑
开发语言·笔记·vscode·macos·unity·游戏引擎
go_bai2 小时前
Linux-线程
linux·开发语言·c++·经验分享·笔记
咖啡の猫2 小时前
Python中的输出函数
开发语言·数据库·python
净03222 小时前
IsaacLab笔记(1)利用standalone python创建场景
笔记·isaacsim·isaaclab
AA陈超2 小时前
ASC学习笔记0022:在不打算修改属性集时访问生成的属性集
c++·笔记·学习·ue5·虚幻引擎·unreal engine
朱一头zcy2 小时前
下载安装pycharm 并通过pycahrm来驱动Anaconda来运行Python程序
ide·python·pycharm