【问题标题】:Unicode-Ascii mixed string in pythonpython中的Unicode-Ascii混合字符串
【发布时间】:2016-07-27 01:42:08
【问题描述】:

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

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 (有 extra )之间的区别。 因此,尽管这个 hacky 解决方案有效,但我想要一个更清洁的解决方案。 我玩了很多 x.encode('utf-8') 等,但还没有工作。

谢谢!

【问题讨论】:

  • 您对数据库有控制权吗?似乎真正的问题是首先像那样存储它。此外,Unicode 是 ASCII 的超集,没有“混合”编码之类的东西。

标签: python string unicode


【解决方案1】:

由于您已经有一个 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 (エアルー)

【讨论】:

    【解决方案2】:
    raw_string = '\u30a8\u30a2\u30eb\u30fc'
    string = ''.join([unichr(int(r, 16)) for r in raw_string.split('\\u') if r])
    print(string)
    

    解决这个问题的方法,期待更好的答案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-09
      • 1970-01-01
      • 2020-03-27
      • 1970-01-01
      • 2013-04-17
      • 1970-01-01
      • 2011-12-26
      • 1970-01-01
      相关资源
      最近更新 更多