Python:将utf8字符串转换为simple的最简单方法是什么

时间:2013-04-05 11:05:40

标签: python html utf-8 string-conversion

我有一个非ASCII字符的utf8字符串。我需要将它以ampersand-hash-digits-semicolon形式放到html文件中。做这个的最好方式是什么?

1 个答案:

答案 0 :(得分: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')
© €