37,719
社区成员
发帖
与我相关
我的任务
分享
dicts = {"a":"中文","b":1}
print str(dicts)
lists = ["中文","a"]
print str(lists)
str3 = "中文"
print str(str3)
In [214]: dicts = {"a":u"中文","b":1}
In [215]: print unicode(dicts)
{'a': u'\u4e2d\u6587', 'b': 1}
In [216]: str(dicts)
Out[216]: "{'a': u'\\u4e2d\\u6587', 'b': 1}"
In [217]: print str(dicts)
{'a': u'\u4e2d\u6587', 'b': 1}
2. 如果\u4e2d这样的表示还不够的话,可以定义自己的__unicode__方法。下面是个简单的例子,你可以按自己的需要定义更复杂的方法。
In [231]: class CustomeUnicode(dict):
...: def __unicode__(self):
...: return '{' + ','.join(unicode(k)+':'+unicode(v) for k, v in self.items()) + '}'
In [232]: dicts2 = CustomeUnicode(dicts)
In [233]: print unicode(dicts2)
{a:中文,b:1}
In [234]: print str(dicts2)
{'a': u'\u4e2d\u6587', 'b': 1}
3. 最后,不知道你要用它干什么,我觉得str的作用基本上就是打印出来看看。要想保存object,以备以后恢复,前面几位推荐的json,repr,以及pickle等更有用。而打印出来看看的话,json.dumps也很好了。所以不建议使用2中提到的办法。>>> a = {"a":"中文","b":1}
>>> import json
>>> print json.dumps(a, encoding="gb2312", ensure_ascii=False)
{"a": "中文", "b": 1}
>>>