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)	# 运行结果:字符串
相关推荐
爱莉希雅&&&2 分钟前
Git 版本控制完整学习笔记
笔记·git·学习
阿图灵3 分钟前
OpenCV 轮廓与属性:查找轮廓、面积周长、形状拟合与点测试
图像处理·人工智能·python·opencv·计算机视觉·轮廓
asdzx675 分钟前
使用 Python 为 Excel 添加各类数据验证规则
开发语言·python·excel
李可以量化24 分钟前
Redis Client 从了解到精通(二)上:redis-py 高级用法与核心命令实战
前端·数据库·redis·python·缓存·ptrade
撩得Android一次心动28 分钟前
Kotlin 语言【知识点整理3】
java·开发语言·笔记·学习·kotlin
Source.Liu31 分钟前
【Dioxus】Dioxus CLI (dx) 命令笔记
笔记·rust·dioxus
2601_9669496536 分钟前
如何利用 1 分钟 K 线在 14:50 精准捕捉尾盘异动?Python 量化实战:1 分钟 K 线 + 全市场扫描
开发语言·人工智能·python·量化·quantdash·量化数据源
海天一色y37 分钟前
强化学习工具函数详解:从经验回放到优势函数计算
人工智能·python·强化学习
CarIise38 分钟前
JavaScript基础语法与DOM操作实战课堂笔记
开发语言·javascript·笔记
pluviophile_s41 分钟前
数据结构:第7讲:图
数据结构·笔记