Python:将UTF8字符串转换为�的最简单方法是什么?

3

我有一个包含非ASCII字符的UTF8字符串。我需要将其以“&#数字;”的形式放入HTML文件中。最佳方法是什么?


正在转换什么,UTF-8字节还是它们所编码的Unicode代码点? - Martijn Pieters
1个回答

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')
© €

@gipi - 是的。已添加一个示例。 - root

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接