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)	# 运行结果:字符串
相关推荐
weixin_580614001 天前
如何提取SQL日期中的年份_使用YEAR或EXTRACT函数
jvm·数据库·python
2301_813599551 天前
SQL生产环境规范_数据库使用最佳实践
jvm·数据库·python
李可以量化1 天前
QMT 量化实战:用 Python 实现线性回归通道,精准识别趋势中的支撑与压力(下)
python·qmt·量化 qmt ptrade
a9511416421 天前
Go 中通过 channel 传递切片时的数据竞争与深拷贝解决方案
jvm·数据库·python
Dxy12393102161 天前
Python 使用正则表达式将多个空格替换为一个空格
开发语言·python·正则表达式
qq_189807031 天前
如何修改RAC数据库名_NID工具在集群环境下的改名步骤
jvm·数据库·python
zhangchaoxies1 天前
如何检测SQL注入风险_利用模糊测试技术发现漏洞
jvm·数据库·python
Luca_kill1 天前
MCP数据采集革命:从传统爬虫到智能代理的技术进化
爬虫·python·ai·数据采集·mcp·webscraping·集蜂云
zhangchaoxies1 天前
CSS如何实现响应式弹性网格布局_配合media query修改flex-wrap属性
jvm·数据库·python
寒秋花开曾相惜1 天前
(学习笔记)第四章 处理器体系结构
linux·网络·数据结构·笔记·学习