encode() 方法使用指定的编码对字符串进行编码。 如果未指定编码,则将使用 UTF-8。
句法
string.encode(encoding, errors)
encoding (可选):一个字符串,指定要使用的编码。 默认为 UTF-8
error(可选):指定错误方法的字符串。 法律价值是:
'backslashreplace' - 使用反斜杠代替无法编码的字符
'ignore' - 忽略无法编码的字符
'namereplace' - 用解释字符的文本替换字符
'strict' - 默认,失败时引发错误
'replace' - 用问号替换字符
'xmlcharrefreplace'- 用 xml 字符替换字符
####### Example 1 #######
my_text = "Hello Stale"
my_text_encoded = my_text.encode()
print(my_text_encoded)
#########################
####### Example 2 #######
my_text = "Hello Stale"
print(my_text.encode(encoding="ascii",errors="backslashreplace"))
print(my_text.encode(encoding="ascii",errors="ignore"))
print(my_text.encode(encoding="ascii",errors="namereplace"))
print(my_text.encode(encoding="ascii",errors="replace"))
print(my_text.encode(encoding="ascii",errors="xmlcharrefreplace"))
#########################
提示:Python 中的所有字符串方法都返回新值,并且它们不会更改原始字符串。