【问题标题】:Python: what is the simplest way to convert utf8 string to �Python:将 utf8 字符串转换为 � 的最简单方法是什么?
【发布时间】:2013-04-05 11:05:39
【问题描述】:

我有一个非 ASCII 字符的 utf8 字符串。我需要将它以&符号哈希数字分号形式放入 html 文件中。做这个的最好方式是什么?

【问题讨论】:

  • 正在转换什么,UTF-8 字节或它们编码的 Unicode 代码点?

标签: python html utf-8 string-conversion


【解决方案1】:

使用.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 - 是的。添加了一个示例。
猜你喜欢
  • 2012-01-07
  • 2021-07-21
  • 2012-08-01
  • 2011-06-06
  • 1970-01-01
  • 1970-01-01
  • 2017-02-14
  • 1970-01-01
  • 2010-09-18
相关资源
最近更新 更多