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)	# 运行结果:字符串
相关推荐
2301_803875611 小时前
PHP 中处理会话数组时的类型错误解析与修复指南
jvm·数据库·python
m0_743623921 小时前
c++如何批量修改文件后缀名_std--filesystem--replace_extension【实战】
jvm·数据库·python
2501_914245932 小时前
CSS如何处理CSS变量作用域冲突_利用特定类名重写变量值
jvm·数据库·python
菜鸟学Python2 小时前
Python生态在悄悄改变:FastAPI全面反超,Django和Flask还行吗?
开发语言·python·django·flask·fastapi
<-->2 小时前
Megatron(全称 Megatron-LM,由 NVIDIA 开发)和 DeepSpeed(由 Microsoft 开发)
人工智能·pytorch·python·深度学习·transformer
测试19983 小时前
2026最新软件测试面试八股文【附文档】
自动化测试·软件测试·python·测试工具·面试·职场和发展·测试用例
handler013 小时前
Linux: 基本指令知识点(2)
linux·服务器·c语言·c++·笔记·学习
maqr_1103 小时前
MySQL数据库迁移到云端如何保障安全_数据加密与SSL连接配置
jvm·数据库·python
u0109147603 小时前
MySQL如何限制触发器递归调用的深度_防止触发器死循环方法
jvm·数据库·python
weixin_381288183 小时前
MySQL中如何使用HEX函数转换十六进制_MySQL进制转换函数
jvm·数据库·python