Python: .encode方法

本文深入解析Python中Unicode字符串的编码与转换方法,包括使用`encode()`函数进行编码及不同错误处理策略如严格、忽略、替换和XML字符引用替代。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

官方教程: http://docs.python.org/2/howto/unicode.html


方法.encode([encoding], [errors='strict']), 返回一个 8-bit string version of the Unicode string, encoded in the requested encoding.

The errors parameter is the same as the parameter of the unicode() constructor, with one additional possibility; as well as ‘strict’,‘ignore’, and ‘replace’, you can also pass ‘xmlcharrefreplace’ which uses XML’s character references. 以下的例子说明了其不同的结果:

>>> u = unichr(40960) + u'abcd' + unichr(1972)
>>> u.encode('utf-8')
'\xea\x80\x80abcd\xde\xb4'
>>> u.encode('ascii')                       
Traceback (most recent call last):
    ...
UnicodeEncodeError: 'ascii' codec can't encode character u'\ua000' in
position 0: ordinal not in range(128)
>>> u.encode('ascii', 'ignore')
'abcd'
>>> u.encode('ascii', 'replace')
'?abcd?'
>>> u.encode('ascii', 'xmlcharrefreplace')
'ꀀabcd޴'

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值