Python将Unicode十六进制utf-8字符串转换为Unicode字符串

2024-05-15 14:49:06 发布

您现在位置:Python中文网/ 问答频道 /正文

s = u'Gaga\xe2\x80\x99s'但需要转换为t = u'Gaga\u2019s'

如何才能最好地实现这一点?


Tags: xe2x80gagau2019sx99s
3条回答

在你解码原始字符串的地方,它很可能是用拉丁语-1或近亲解码的。由于latin-1是Unicode的前256个码位,因此可以:

>>> s = u'Gaga\xe2\x80\x99s'
>>> s.encode('latin-1').decode('utf8')
u'Gaga\u2019s'
s = u'Gaga\xe2\x80\x99s'
t = u'Gaga\u2019s'
x = s.encode('raw-unicode-escape').decode('utf-8')
assert x==t

print(x)

收益率

Gaga’s
import codecs

s = u"Gaga\xe2\x80\x99s"
s_as_str = codecs.charmap_encode(s)[0]
t = unicode(s_as_str, "utf-8")
print t

印刷品

u'Gaga\u2019s'

相关问题 更多 >