python中字符串类型的encode()方法_Python 字符串 encode() 方法

Python字符串encode()方法

例如:

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"))

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值