[英]Python Convert Unicode-Hex utf-8 strings to Unicode strings
有s = u'Gaga\\xe2\\x80\\x99s'
但需要轉換為t = u'Gaga\’s'
如何才能最好地實現這一目標?
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
無論你解密原始字符串,它都可能用latin-1或近親解碼。 由於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
版畫
u'Gaga\u2019s'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.