简体   繁体   English

将Unicode字符打印为python对象内的转义序列

[英]Unicode characters printed as escape sequences inside python object

I am using python 2.7.13. 我正在使用python 2.7.13。 My python script generates a dictionary, which contains Hebrew. 我的python脚本生成了一个字典,其中包含希伯来语。

The code is as follows, 代码如下,

# -*- coding: utf-8 -*-

val = "אבג".decode('utf-8')
print val
dict = {
        'attributes' : {
        'OBJECTID_1' : 1,
        'LOCID' : val
         }
}
print dict

The results are as follows, 结果如下,

אבג
{'attributes': {'LOCID': u'\u05d0\u05d1\u05d2', 'OBJECTID_1': 1}}

The first result shows as expected, since we use 'print'. 由于我们使用“打印”,因此第一个结果按预期显示。 However, in the dictionary I created, the Hebrew shows as unicode. 但是,在我创建的字典中,希伯来语显示为unicode。

Is there anyway to display actual Hebrew in my dictionary? 无论如何,在我的词典中是否可以显示实际的希伯来语? Or is this expected? 还是这是预期的?

Thanks 谢谢

In python2, when you print out a list, you end up printing the repr of the contents of that list. 在python2中,当您打印出一个列表时,最终将打印该列表内容的repr

In python3, a string's repr is the same as its str return value. 在python3中,字符串的repr与其str返回值相同。 You can observe this below: 您可以在下面观察到这一点:

Python2 Python2

>>> val = "אבג".decode('utf-8')
>>> val         # displays repr value
u'\u05d0\u05d1\u05d2'
>>> print val   # displays str value
אבג

And, as mentioned, 而且,如上所述

>>> print [val]
[u'\u05d0\u05d1\u05d2']

Constrasting with python3, str objects do not have a decode function - they are already decoded. 与python3相比, str对象没有decode功能-它们已被解码。

>>> val = "אבג"
>>> val
'אבג'
>>> print(val)
אבג
>>> print([val])
['אבג']

You can see this is why it works now. 您可以看到这就是为什么它现在可以工作的原因。

For your problem, if you want to view the character as it is when you print the dict, you can do this: 对于您的问题,如果要在打印字典时按原样查看字符,可以执行以下操作:

print dict['LOCID']

Side note, do not use dict to name variables since it shadows the very important builtin class you are using. 旁注,请勿使用dict来命名变量,因为它掩盖了您正在使用的非常重要的内置类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM