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)	# 运行结果:字符串
相关推荐
马克Markorg7 分钟前
基于LLM的大模型的RAG(检索增强生成)实现对比
python·大模型·agent·rag·企业级知识库的框架·rag 知识库
yy.y--13 分钟前
Java线程实现浏览器实时时钟
java·linux·开发语言·前端·python
Dontla18 分钟前
Python Streamlit介绍(开源Python Web应用框架,快速将Python脚本转换成交互式Web应用,适合数据科学和机器学习项目快速展示)
前端·python·开源
少云清38 分钟前
【UI自动化测试】12_web自动化测试 _验证码处理和cookie
前端·python·web自动化测试
Ama_tor1 小时前
Flask |零基础进阶(上)
后端·python·flask
喵手1 小时前
Python爬虫实战:数字时光机 - 基于 Playwright 的网页全貌归档系统(HTML + 截图)(附CSV导出 + SQLite持久化存储)!
爬虫·python·爬虫实战·playwright·零基础python爬虫教学·csv导出·网页全貌归档
@陈小鱼1 小时前
基于 Savitzky-Golay滤波器的超声图像运动分析方法
python·计算机视觉·matlab·信号处理
七夜zippoe1 小时前
属性测试革命:Hypothesis框架深度实战指南
python·性能测试·数据驱动·hypothesis·状态机测试
蒸蒸yyyyzwd1 小时前
os八股学习笔记
笔记·学习
Yeh2020581 小时前
2月14日笔记
笔记