开发手册 欢迎您!
软件开发者资料库

Python 字符串 encode() 方法

Python有一组可以用于字符串的内置方法。Python 字符串操作常用操作,如字符串的替换、删除、截取、赋值、连接、比较、查找、分割等。本文主要介绍Python 字符串 encode() 方法

Python字符串encode()方法

Python 字符串方法

例如:

UTF-8编码字符串:

txt = "My name is Ståle"x = txt.encode()print(x)

1、定义和用法

encode()方法使用指定的编码对字符串进行编码。如果未指定编码,则将使用UTF-8。

2、调用语法

string.encode(encoding=encoding, errors=errors)

3、参数说明

参数说明
encoding可选的。指定要使用的编码的字符串。默认的是UTF-8
errors可选的。指定error方法的字符串,可以取的值是:
'backslashreplace'使用反斜杠代替无法编码的字符
'ignore'忽略不能编码的字符
'namereplace'用解释该字符的文本替换该字符
'strict'默认,失败时抛出错误
'replace'用问号替换字符
'xmlcharrefreplace'以xml字符替换

4、使用示例

例如:

这些示例使用ascii编码和无法编码的字符,显示带有不同错误的结果:

txt = "My name is Ståle"print(txt.encode(encoding="ascii",errors="backslashreplace"))print(txt.encode(encoding="ascii",errors="ignore"))print(txt.encode(encoding="ascii",errors="namereplace"))print(txt.encode(encoding="ascii",errors="replace"))print(txt.encode(encoding="ascii",errors="xmlcharrefreplace"))

Python 字符串方法