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)	# 运行结果:字符串
相关推荐
东莞市云毅网络有限公司1 小时前
用 Node 做收录快照的周对比:差集、阈值与告警
python·sqlite·自动化运维·geo·数据监测
山楂树の2 小时前
Python Pandas 数据处理:数据读取、筛选、清洗、排序与分组
开发语言·python·pandas
一只大鸽子2 小时前
游戏开发笔记17-Godot RPG游戏基础-菜单
笔记·游戏·godot
Logintern093 小时前
langgraph 图编译的聊天机器人
python·langgraph
xurileidian3 小时前
第 22 篇 · 边玩边学Python · 双等号与 is 不是一回事
开发语言·python·spring
ever_you_love4 小时前
12.1课堂笔记
笔记
钱栈up5 小时前
GitHub热榜实测|Sherlock:一个用户名搜遍全网
python·开源·github
geovindu5 小时前
python: Gradient Boosting
开发语言·后端·python·算法·boosting
卿卿的产品经理日记5 小时前
【AI产品经理实战】Day 48|AI 回答变短了,到底是谁的功劳?
人工智能·笔记·aigc·产品经理
Agent世界6 小时前
发布台账字段漂移:1265 条记录里 190 条没有标题
python·自动化运维