【问题标题】:python: convert to HTML special characters [duplicate]python:转换为HTML特殊字符[重复]
【发布时间】:2012-06-15 03:50:37
【问题描述】:

可能重复:
Replace html entities with the corresponding utf-8 characters in Python 2.6
What's the easiest way to escape HTML in Python?

有一种方法可以轻松地将字符串转换为 HTML 字符串, 例如用 等字符替换为 < > 还是我必须编写自己的转换程序???

【问题讨论】:

标签: python html


【解决方案1】:

如果您只关心&<> 等关键特殊字符:

>>> import cgi
>>> cgi.escape("<hello&goodbye>")
'&lt;hello&amp;goodbye&gt;'

对于其他非 ASCII 字符:

>>> "Übeltäter".encode("ascii", "xmlcharrefreplace")
b'&#220;belt&#228;ter'

当然,如果需要,你可以将两者结合起来:

>>> cgi.escape("<Übeltäter>").encode("ascii", "xmlcharrefreplace")
b'&lt;&#220;belt&#228;ter&gt;'

【讨论】:

  • &gt;&gt;&gt; "Übeltäter".encode("ascii", "xmlcharrefreplace") 导致UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128)
  • cgi.escape() 现在已弃用。请改用html.escape() - 检查this answer
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-09-19
  • 2011-04-22
  • 1970-01-01
  • 2015-02-20
  • 1970-01-01
  • 1970-01-01
  • 2017-05-30
相关资源
最近更新 更多