Skip to main content
 首页 » 编程设计

python之python中的Unicode-Ascii混合字符串

2025年05月04日39bonelee

我有一个字符串存储在数据库中:

FB (\u30a8\u30a2\u30eb\u30fc) 

当我从 python 代码加载这一行时,我无法正确格式化它。

# x = load that string 
print x # returns u'FB (\\u30a8\\u30a2\\u30eb\\u30fc)' 

注意两个“\”,这会弄乱前端的 unicode 字符 html 没有显示外来字符,而是将其显示为\u30a8\u30a2\u30eb\u30fc

但是,如果我加载追加一些字符以将其转换为 json 格式并加载 json,我会得到预期的结果。

s = '{"a": "%s"}'%x 
json.loads(s)['a'] 
#prints u'FB (\u30a8\u30a2\u30eb\u30fc)' 

请注意此结果(在前端正确显示)与直接打印 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 (エアルー)