Man*_*dhe 1 python string unicode
我有一个存储在DB中的字符串:
FB (\u30a8\u30a2\u30eb\u30fc)
Run Code Online (Sandbox Code Playgroud)
当我从python代码加载此行时,我无法正确格式化它.
# x = load that string
print x # returns u'FB (\\u30a8\\u30a2\\u30eb\\u30fc)'
Run Code Online (Sandbox Code Playgroud)
注意两个"\"这会弄乱前端的unicode字符而不是显示外来字符,html将其显示为\ u30a8\u30a2\u30eb\u30fc
但是,如果我加载附加一些字符将其转换为json格式并加载json,我得到预期的结果.
s = '{"a": "%s"}'%x
json.loads(s)['a']
#prints u'FB (\u30a8\u30a2\u30eb\u30fc)'
Run Code Online (Sandbox Code Playgroud)
注意这个结果(在前端正确显示)和直接打印x(有额外的)之间的区别.虽然这个hacky解决方案有效,但我想要一个更清洁的解决方案.我用x.encode('utf-8')等玩过很多次,但是还没有用.
谢谢!
由于您已经有一个Unicode字符串,请将其编码回ASCII并使用unicode_escape编解码器对其进行解码:
>>> s = u'FB (\\u30a8\\u30a2\\u30eb\\u30fc)'
>>> s
u'FB (\\u30a8\\u30a2\\u30eb\\u30fc)'
>>> print s
FB (\u30a8\u30a2\u30eb\u30fc)
>>> s.encode('ascii').decode('unicode_escape')
u'FB (\u30a8\u30a2\u30eb\u30fc)'
>>> print s.encode('ascii').decode('unicode_escape')
FB (????)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1086 次 |
| 最近记录: |