【发布时间】:2011-09-30 11:36:45
【问题描述】:
有s = u'Gaga\xe2\x80\x99s'但需要转换成t = u'Gaga\u2019s'
如何才能最好地做到这一点?
【问题讨论】:
有s = u'Gaga\xe2\x80\x99s'但需要转换成t = 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
【讨论】:
print repr(t) 仍然产生'Gaga\xe2\x80\x99s'
looks like he fixed that.
无论您在何处解码原始字符串,它都可能使用 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'
【讨论】:
codecs.charmap_encode,链接?