2013-04-05 68 views

回答

2

使用.encode方法與'xmlcharrefreplace'作爲errors參數傳遞:

In [1]: help(unicode.encode) 
Help on method_descriptor: 

encode(...) 
    S.encode([encoding[,errors]]) -> string or unicode 

    Encodes S using the codec registered for encoding. encoding defaults 
    to the default encoding. errors may be given to set a different error 
    handling scheme. 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. 

In [2]: ustr = u'\xa9 \u20ac' 

In [3]: print ustr 
© € 

In [4]: print ustr.encode('ascii', 'xmlcharrefreplace') 
© € 
+0

'ustr'我想是一個Unicode字符串(?) – gipi 2013-04-05 11:12:19

+0

@gipi - 是的。增加了一個例子。 – root 2013-04-05 11:14:10

+0

偉大的解決方案,非常感謝 – dimitri 2013-04-05 12:34:54

相關問題