【问题标题】:Behaviour unicode string in pythonpython中的行为unicode字符串
【发布时间】:2015-09-01 04:40:36
【问题描述】:

我看过这个question 我对如何在运行时将 var 转换为 unicode 有疑问? 使用unicode函数是否正确? 还有其他方法可以在运行时转换字符串吗?

print(u'Cami\u00f3n') # prints with right special char

name=unicode('Cami\u00f3n')
print(name) # prints bad ===> Cami\u00f3n

name.encode('latin1')
print(name.decode('latin1')) # prints bad ===> Cami\u00f3n

encoded_id = u'abcd\xc3\x9f'
encoded_id.encode('latin1').decode('utf8')
print encoded_id.encode('latin1').decode('utf8') # prints right

我在 stackoverflow 上看到很多 python unicode 问题,但我无法理解这种行为。

【问题讨论】:

  • 你想做什么?您要转换什么数据?这个从哪里来? “按运行时间”是什么意思?
  • \uhhhh 转义序列仅适用于 Python unicode 文字。如果你有带有这种转义序列的数据,你很可能有 JSON 数据,它使用相同的语法。如果是这样,请对该数据使用 JSON 解析器。
  • 您可以要求 Python 使用特殊的编解码器来解释此类序列,但这通常是对数据的错误解释。请分享您的实际数据样本,以便我们为您提供帮助。

标签: python python-3.x unicode


【解决方案1】:

正因为如此,如果您没有为unicode 函数指定任何编码,那么:

unicode() 将模仿 str() 的行为,只是它返回 Unicode 字符串而不是 8 位字符串。更准确地说,如果 object 是 Unicode 字符串或子类,它将返回该 Unicode 字符串而不应用任何额外的解码。

因此,您将拥有一个 str 版本的 unicode(Unicode 部分将被转义):

>>> name=unicode('Cami\u00f3n')
>>> print(name)
Cami\u00f3n
>>> name
u'Cami\\u00f3n'
       ^ 

为了解决这个问题,您可以使用 'unicode-escape' 作为编码来避免将 Unicode 转换为字符串!

>>> name=unicode('Cami\u00f3n','unicode-escape')
>>> name
u'Cami\xf3n'
>>> print(name)
Camión

【讨论】:

  • 像魅力一样工作。我试图用它来打印带有特殊字符的数据库中的数据以进行代码测试。谢谢!
  • 请注意,unicode-escape 解释 更多 而不仅仅是 \uhhhh 转义。如果文本中还有其他 `\` 反斜杠转义符,它们也会被解释,并且可能不是您所期望的。
  • @Ulyarez 欢迎,也请注意 Martijn 的评论!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-19
  • 1970-01-01
  • 2011-11-12
  • 2021-11-03
  • 1970-01-01
相关资源
最近更新 更多