Python_encode编码和decode解码

encode 用法详解

  1. 将 Unicode 编码字符转化成其他编码的字符串,如 str.encode(‘gb2312’) 将 Unicode 编码字符转化成 gb2312 编码的字符。
  2. 这里的 str 是 Unicode string,如 ‘一’ 或 ‘\u4e00’。
  3. encode 默认 utf-8 码。
>>> help(str.encode)
Help on built-in function encode:

encode(encoding='utf-8', errors='strict') method of builtins.str instance
    Encode the string using the codec registered for encoding.
    
    encoding
      The encoding in which to encode the string.
    errors
      The error handling scheme to use for encoding errors.
      The default is 'strict' meaning that encoding errors raise a
      UnicodeEncodeError.  Other possible values are 'ignore', 'replace' and
      'xmlcharrefreplace' as well as any other name registered with
      codecs.register_error that can handle UnicodeEncodeErrors.
>>> str1='一'
>>> str1.encode()
b'\xe4\xb8\x80'
>>> str1.encode('utf-16')
b'\xff\xfe\x00N'
>>> str1.encode('gb2312')
b'\xd2\xbb'
>>> str1.encode('gbk')
b'\xd2\xbb'
>>> str1.encode('ASCII')
Traceback (most recent call last):
  File "<pyshell#86>", line 1, in <module>
    str1.encode('ASCII')
UnicodeEncodeError: 'ascii' codec can't encode character '\u4e00' in position 0: ordinal not in range(128)
>>> str1.encode('ASCII', 'ignore')  #忽略不能编码的字符,结果中不包含不能编码的字符,且没有任何提示
b''
>>> str1.encode('ASCII', 'replace')  #使用问号 ? 替换不能进行编码的字符
b'?'

decode 用法详解

  1. 将其他编码的 字符串 转化成 Unicode string,如 str.decode(‘utf-8’) 将 utf-8 字符串转化为 Unicode 编码。
  2. 这里的 str 是 decode 里对应的编码字符。
  3. decode 后的结果是认识的 Unicode string,如 ‘一’ 而不是 ‘\u4e00’。
>>> import chardet
>>> str2 = b'\xff\xfe\x00N'
>>> chardet.detect(str2) 
{'encoding': 'UTF-16', 'confidence': 1.0, 'language': ''}
>>> chardet.detect(str2)['encoding']  #查阅是什么编码字符
'UTF-16'
>>> str2.decode('UTF-16')
'一'
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值