简体   繁体   English

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

[英]Python Convert Unicode-Hex utf-8 strings to Unicode strings

Have s = u'Gaga\\xe2\\x80\\x99s' but need to convert to t = u'Gaga\’s' s = u'Gaga\\xe2\\x80\\x99s'但需要转换为t = u'Gaga\’s'

How can this be best achieved? 如何才能最好地实现这一目标?

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

print(x)

yields 产量

Gaga’s

Where ever you decoded the original string, it was likely decoded with latin-1 or a close relative. 无论你解密原始字符串,它都可能用latin-1或近亲解码。 Since latin-1 is the first 256 codepoints of Unicode, this works: 由于latin-1是Unicode的前256个代码点,因此可以:

>>> s = u'Gaga\xe2\x80\x99s'
>>> s.encode('latin-1').decode('utf8')
u'Gaga\u2019s'
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

prints 版画

u'Gaga\u2019s'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM