请教下 python 的 dict,有 unicode 该如何解决

2014-02-20 05:33:29 +08:00
 kchum
python不太熟
代码如下,我想取得dst对应的值:音乐(\u97f3\u4e50)

t={u'src': u'[ Music ]', u'dst': u'\u97f3\u4e50'}
rs=t.get('dst')
print(rs)

print(rs.decode('utf-8').encode('ascii'))

用过decode,encode...
提示UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128)

网上查过试过
reload(sys)
sys.setdefaultencoding( "utf-8" )

没效果,测试过,就是print的时候才提示错误的。。试了2个小时,唉。

环境python 2.7.5
7249 次点击
所在节点    Python
9 条回复
xhacker
2014-02-20 06:57:02 +08:00
你到底想获得什么?rs 现在已经是一个 unicode 字符串了啊。
kchum
2014-02-20 07:30:06 +08:00
@xhacker 我是希望能print出来,现在print的时候会提示UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2
pt
2014-02-20 07:47:47 +08:00
直接:
print(rs.encode('utf-8'))

参考:http://stackoverflow.com/a/492711/114833
tempdban
2014-02-20 07:48:32 +08:00
直接print 另外ide的console基本没有中文支持
geew
2014-02-20 09:11:43 +08:00
In [1]: t={u'src': u'[ Music ]', u'dst': u'\u97f3\u4e50'}

In [2]: rs=t.get('dst')

In [3]: print(rs) # 直接print就行了啊
音乐

In [4]: print(rs.decode('utf-8').encode('ascii')) # 中文encode ascii肯定会报这个错
---------------------------------------------------------------------------
UnicodeEncodeError Traceback (most recent call last)
/home/geew/familyparty/<ipython-input-4-72fd90a6715b> in <module>()
----> 1 print(rs.decode('utf-8').encode('ascii'))
kchum
2014-02-20 12:33:57 +08:00
@tempdban
@geew
@pt
@xhacker
感谢各位关注,正解如4楼所说
折腾半天,原来是Pycharm的终端没有中文支持。
exoticknight
2014-02-20 13:02:30 +08:00
C:\Python27\python.exe Z:/python/pyqttest/main.py
中文哦

Process finished with exit code 0

怎么我能print得出来……
kchum
2014-02-20 14:48:46 +08:00
@exoticknight 是Pycharm的Terminal不支持unicode吧,我是在IDE里面调试的。用iTerm则没有出错
exoticknight
2014-02-20 17:54:16 +08:00
@kchum
非要我截图吗,贴图好麻烦……
http://www.image-share.com/ijpg-2444-111.html

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/101005

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX