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)	# 运行结果:字符串
相关推荐
nimadan123 小时前
**AI漫剧软件2025推荐,解锁高性价比创意制作新体验**
人工智能·python
雾岛听蓝5 小时前
C++11新特性(lambda、包装器)
c++·经验分享·笔记
yunhuibin5 小时前
GoogLeNet学习
人工智能·python·深度学习·神经网络·学习
易辰君6 小时前
【Python爬虫实战】正则:中文匹配与贪婪非贪婪模式详解
开发语言·爬虫·python
秀儿还能再秀6 小时前
正则表达式核心语法 + Python的 re 库中常用方法
python·正则表达式
xcLeigh6 小时前
Python入门:Python3 正则表达式全面学习教程
python·学习·正则表达式·教程·python3
代码游侠7 小时前
Linux驱动复习——驱动
linux·运维·arm开发·笔记·学习
多恩Stone7 小时前
【C++ debug】在 VS Code 中无 Attach 调试 Python 调用的 C++ 扩展
开发语言·c++·python
枷锁—sha7 小时前
【CTFshow-pwn系列】03_栈溢出【pwn 053】详解:逐字节爆破!手写 Canary 的终极破解
网络·笔记·安全·网络安全
XW01059998 小时前
4-11判断素数
前端·python·算法·素数