Python 字符串 encode() 方法

实例

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

  1. txt = "My name is Ståle"
  2. x = txt.encode()
  3. 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. print(txt.encode(encoding="ascii",errors="backslashreplace"))
  3. print(txt.encode(encoding="ascii",errors="ignore"))
  4. print(txt.encode(encoding="ascii",errors="namereplace"))
  5. print(txt.encode(encoding="ascii",errors="replace"))
  6. print(txt.encode(encoding="ascii",errors="xmlcharrefreplace"))
  7. print(txt.encode(encoding="ascii",errors="strict"))

分类导航