在python对象中打印为转义序列的Unicode字符

在python对象中打印为转义序列的Unicode字符,python,python-2.7,Python,Python 2.7,我正在使用python 2.7.13。我的python脚本生成一个包含希伯来语的字典 代码如下: # -*- coding: utf-8 -*- val = "אבג".decode('utf-8') print val dict = { 'attributes' : { 'OBJECTID_1' : 1, 'LOCID' : val } } print dict אבג {'attributes': {'LOCID': u'

我正在使用python 2.7.13。我的python脚本生成一个包含希伯来语的字典

代码如下:

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

val = "אבג".decode('utf-8')
print val
dict = {
        'attributes' : {
        'OBJECTID_1' : 1,
        'LOCID' : val
         }
}
print dict
אבג
{'attributes': {'LOCID': u'\u05d0\u05d1\u05d2', 'OBJECTID_1': 1}}
结果如下:

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

val = "אבג".decode('utf-8')
print val
dict = {
        'attributes' : {
        'OBJECTID_1' : 1,
        'LOCID' : val
         }
}
print dict
אבג
{'attributes': {'LOCID': u'\u05d0\u05d1\u05d2', 'OBJECTID_1': 1}}
第一个结果如预期所示,因为我们使用了“print”。然而,在我创建的字典中,希伯来语显示为unicode

在我的字典里有没有真正的希伯来语?或者这是预期的结果


谢谢

在python2中,当您打印列表时,您最终会打印该列表内容的
repr

在python3中,字符串的
repr
与其
str
返回值相同。您可以在下面看到这一点:

蟒蛇2

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

>>> print [val]
[u'\u05d0\u05d1\u05d2']
与python3相比,
str
对象没有
decode
功能-它们已经被解码了

>>> val = "אבג"
>>> val
'אבג'
>>> print(val)
אבג
>>> print([val])
['אבג']
你可以看到这就是为什么它现在起作用

对于您的问题,如果您希望在打印dict时查看字符,可以执行以下操作:

print dict['LOCID']

请注意,不要使用
dict
命名变量,因为它会隐藏您正在使用的非常重要的内置类。

没关系。您要做的是打印字符串的
repr
。您可以确认这一点:一个简单的修复程序将切换到Python3,而现在还不算太晚;u'\u05d0\u05d1\u05d2';>>打印val;אבג另外,
dict
python
中的保留关键字,不建议将其用作identifier@GhilasBELHADJ:从技术上讲,
dict
既不是保留的,也不是关键字,而是内置的。不过,你还是不应该重新定义它。谢谢你的回复。这是有道理的。我想我将直接使用python 3。