Python: .encode方法

官方教程: 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޴'

發佈了118 篇原創文章 · 獲贊 0 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章