gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 00:10:05 25 4
gpt4 key购买 nike

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

最佳答案

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

关于Python:将utf8字符串转换为�的最简单方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15832276/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com