Python将Unicode-Hex utf-8字符串转换为Unicode字符串

Hen*_*ton 5 python unicode utf-8

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

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

unu*_*tbu 8

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

print(x)
Run Code Online (Sandbox Code Playgroud)

产量

Gaga’s
Run Code Online (Sandbox Code Playgroud)

  • @dbv:在研究了这个之后,我认为Mark Tolonen有更好的答案.为了让SO报告最佳答案,请考虑接受[他的回答](http://stackoverflow.com/questions/7609776/python-convert-unicode-hex-utf-8-strings-to- unicode-strings/7610946#7610946)相反. (3认同)

Mar*_*nen 7

无论你解密原始字符串,它都可能用latin-1或近亲解码.由于latin-1是Unicode的前256个代码点,因此可以:

>>> s = u'Gaga\xe2\x80\x99s'
>>> s.encode('latin-1').decode('utf8')
u'Gaga\u2019s'
Run Code Online (Sandbox Code Playgroud)