Python3 中的 encode()函数

首页 / Python3入门教程 / Python3 中的 encode()函数

Python encode()方法根据提供的编码标准对字符串进行编码。默认情况下,Python字符串采用unicode格式,但也可以编码为其他标准。

编码是将文本从一种标准代码转换为另一种标准代码的过程。

encode - 语法

encode(encoding="utf-8", errors="strict")

encode - 参数

  • encoding   -  编码标准,默认为UTF-8
  • errors         -  错误模式,以忽略或替换错误消息。

两者都是可选的。默认编码为UTF-8。

encode - 返回类型

它返回一个编码的字符串。

一种将unicode字符串编码为utf-8编码标准的简单方法。

# Python encode() function example
# 变量声明
str = "HELLO"
encode = str.encode()
# 显示结果
print("Old value", str)
print("Encoded value", encode)

输出

Old value HELLO
Encoded value b 'HELLO'

无涯教程正在编码一个拉丁字符

? into default encoding.
# Python encode() function example
# 变量声明
str = "HËLLO"
encode = str.encode()
# 显示结果
print("Old value", str)
print("Encoded value", encode)

输出

Old value HËLLO
Encoded value b'H\xc3\x8bLLO'

正在将拉丁字符编码为ascii,它会引发错误。参见下面的例子

链接:https://www.learnfk.comhttps://www.learnfk.com/python3/python-string-encode-method.html

来源:LearnFk无涯教程网

# Python encode() function example
# 变量声明
str = "HËLLO"
encode = str.encode("ascii")
# 显示结果
print("Old value", str)
print("Encoded value", encode)

输出

UnicodeEncodeError: 'ascii' codec can't encode character '\xcb' in position 1: ordinal not in range(128)

如果无涯教程想忽略错误,则将ignore作为第二个参数传递。

# Python encode() function example
# 变量声明
str = "HËLLO"
encode = str.encode("ascii","ignore")
# 显示结果
print("Old value", str)
print("Encoded value", encode)

输出

Old value HËLLO
Encoded value b'HLLO'

它忽略错误并用?替换字符。标记。

# Python encode() function example
# 变量声明
str = "HËLLO"
encode = str.encode("ascii","replace")
# 显示结果
print("Old value", str)
print("Encoded value", encode)

输出

Old value HËLLO
Encoded value b'H?LLO'

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

Java核心技术面试精讲 -〔杨晓峰〕

如何做好一场技术演讲 -〔极客时间〕

高并发系统设计40问 -〔唐扬〕

罗剑锋的C++实战笔记 -〔罗剑锋〕

恋爱必修课 -〔李一帆〕

Spring编程常见错误50例 -〔傅健〕

操作系统实战45讲 -〔彭东〕

云原生架构与GitOps实战 -〔王炜〕

徐昊 · AI 时代的软件工程 -〔徐昊〕

好记忆不如烂笔头。留下您的足迹吧 :)