ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

python字符串-编码(encode)

2022-04-05 22:35:01  阅读:199  来源: 互联网

标签:编码 utf encoding python x88 strict encode


encode方法用于使用指定的编码格式对字符串进行编码。

语法

encode(encoding='utf-8', errors='strict')

参数

  • encoding: 编码格式,默认为‘utf-8’。
  • errors: 不同错误的处理方案,默认值为strict。
    • strict:遇到非法字符就抛出异常。
    • ignore:忽略非法字符。
    • replace:用“?”替换非法字符。
    • xmlcharrefreplace:使用 xml 的字符引用。

返回值

  • 编码后的字符串。

示例

str = '我爱我的爸妈'
print('默认为utf-8编码:', str.encode())
print('utf-8明示编码:', str.encode('UTF-8'))
print('GBK编码:', str.encode('GBK', 'strict'))
try:
    print('BIG5编码:', str.encode('BIG5', 'strict'))
except UnicodeError as err:
    print('出错了:', err)

print('BIG5编码,igonre参数忽略非法字符:', str.encode('BIG5', 'ignore'))
默认为utf-8编码: b'\xe6\x88\x91\xe7\x88\xb1\xe6\x88\x91\xe7\x9a\x84\xe7\x88\xb8\xe5\xa6\x88'
utf-8明示编码: b'\xe6\x88\x91\xe7\x88\xb1\xe6\x88\x91\xe7\x9a\x84\xe7\x88\xb8\xe5\xa6\x88'
GBK编码: b'\xce\xd2\xb0\xae\xce\xd2\xb5\xc4\xb0\xd6\xc2\xe8'
出错了: 'big5' codec can't encode character '\u7231' in position 1: illegal multibyte sequence
BIG5编码,igonre参数忽略非法字符: b'\xa7\xda\xa7\xda\xaa\xba\xaa\xa8'

help()

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.

标签:编码,utf,encoding,python,x88,strict,encode
来源: https://www.cnblogs.com/freepc/p/16104294.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有