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)	# 运行结果:字符串
相关推荐
ScilogyHunter2 分钟前
SCons:Python驱动的智能构建系统
python·构建系统·scons
luoluoal9 分钟前
基于python的基于深度学习的车俩特征分析系(源码+文档)
python·mysql·django·毕业设计·源码
航Hang*14 分钟前
Photoshop 图形与图像处理技术——第9章:实践训练1——绘制禁烟标志和奥运五环
图像处理·笔记·学习·ui·photoshop
轻竹办公PPT17 分钟前
2026 年 AI 办公趋势:AI 生成 PPT 工具谁在领先
人工智能·python
saoys29 分钟前
Opencv 学习笔记:图像金字塔实现上采样(pyrUp)与降采样(pyrDown)
笔记·opencv·学习
Kingairy39 分钟前
Python面试高频题
java·python·面试
黎雁·泠崖40 分钟前
Java数组入门:定义+静态/动态初始化全解析(隐式转换+案例+避坑指南)
java·开发语言·python
梅羽落41 分钟前
fastapi速成2
python·github·fastapi
灵活用工平台1 小时前
灵活用工平台注册流程图
python·流程图
2501_905967331 小时前
双目视觉:CREStereo论文超详细解读
人工智能·python·计算机视觉·双目视觉