Python 字符串 encode() 方法

实例

对字符串进行 UTF-8 编码:

  1. txt = "My name is Ståle"
  2.  
  3. x = txt.encode()
  4.  
  5. print(x)

定义和用法

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

语法

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

参数值

参数 描述
encoding 可选。字符串。规定要使用的编码。默认是 UTF-8。
errors 可选。字符串。规定错误方法。合法值是: 'backslashreplace' - 使用反斜杠代替无法编码的字符 'ignore' - 忽略无法编码的字符 'namereplace' - 用解释字符的文本替换字符 'strict' - 默认值,失败时引发错误 'replace' - 用问号替换字符 'xmlcharrefreplace' - 用 xml 字符替换字符

更多实例

实例

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

  1. txt = "My name is Ståle"
  2.  
  3. print(txt.encode(encoding="ascii",errors="backslashreplace"))
  4. print(txt.encode(encoding="ascii",errors="ignore"))
  5. print(txt.encode(encoding="ascii",errors="namereplace"))
  6. print(txt.encode(encoding="ascii",errors="replace"))
  7. print(txt.encode(encoding="ascii",errors="xmlcharrefreplace"))
  8. print(txt.encode(encoding="ascii",errors="strict"))