Python str.decode

String Decode方法


功能描述

decode方法对使用编码的字符串进行解码。

语法

Str.decode(encoding='UTF-8',errors='strict')

参数

  • encoding:使用的编码
  • errors:设置不同的错误处理方案。默认值是’strict’,表示编码的错误将引发UnicodeError。其他可能的值是’ignore’, ‘replace’, ‘xmlcharrefreplace’, 'backslashreplace’和其他通过codecs.register_error()注册的名称。

返回值

解码的字符串

示例

Str = "你好"
Str = Str.encode('utf-8','strict')
print("Encoded String: ",Str)
print("Decoded String: " + Str.decode('utf-8','strict'))

执行结果

Encoded String:  b'\xe4\xbd\xa0\xe5\xa5\xbd'
Decoded String: 你好

如果编码与解码方式不一样,且更改错误码后

print("Decoded String: " + Str.decode('gb2312','ignore'))
print("Decoded String: " + Str.decode('gb2312','replace'))
print("Decoded String: " + Str.decode('gb2312','backslashreplace'))
print("Decoded String: " + Str.decode('gb2312','xmlcharrefreplace'))

执行结果

Decoded String: 浣濂
Decoded String: 浣�濂�
Decoded String: 浣\xa0濂\xbd
TypeError: decoding with 'gb2312' codec failed (TypeError: don't know how to handle UnicodeDecodeError in error callback)

Error的处理机制

  • ignore:忽略错误解析的数据,编码或解码将继续,且不通报;
  • replace:将编码错误替换为?;将解码错误替换为�
  • backslashreplace:将格式错误数据替换为反斜线转义序列
  • xmlcharrefreplace:不可替换的字符由适当的XML字符引用替换
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值