您的位置:首页 > 编程语言 > Python开发

Python: .encode方法

2013-11-29 16:53 169 查看
官方教程: 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޴'
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: