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)	# 运行结果:字符串
相关推荐
西柚与蓝莓41 分钟前
【开源开放体系总结】
python
belldeep4 小时前
python:reportlab 将多个图片合并成一个PDF文件
python·pdf·reportlab
FreakStudio6 小时前
全网最适合入门的面向对象编程教程:56 Python字符串与序列化-正则表达式和re模块应用
python·单片机·嵌入式·面向对象·电子diy
丶21366 小时前
【CUDA】【PyTorch】安装 PyTorch 与 CUDA 11.7 的详细步骤
人工智能·pytorch·python
_.Switch7 小时前
Python Web 应用中的 API 网关集成与优化
开发语言·前端·后端·python·架构·log4j
一个闪现必杀技7 小时前
Python入门--函数
开发语言·python·青少年编程·pycharm
小鹿( ﹡ˆoˆ﹡ )8 小时前
探索IP协议的神秘面纱:Python中的网络通信
python·tcp/ip·php
卷心菜小温8 小时前
【BUG】P-tuningv2微调ChatGLM2-6B时所踩的坑
python·深度学习·语言模型·nlp·bug
陈苏同学8 小时前
4. 将pycharm本地项目同步到(Linux)服务器上——深度学习·科研实践·从0到1
linux·服务器·ide·人工智能·python·深度学习·pycharm
唐家小妹8 小时前
介绍一款开源的 Modern GUI PySide6 / PyQt6的使用
python·pyqt