print list 无法显示中文

 -*- coding: utf-8 -*-

print ["asdf", "中文"]
print ["中文"]
print "中文"

The output in the Eclipse console is very strange:

['asdf', '\xe4\xb8\xad\xe6\x96\x87']
['\xe4\xb8\xad\xe6\x96\x87']
中文

My first question is: why did the last line get the correct output, and the others didn't?

And my second question is: how do I correct the wrong ones (to make them output real characters instead of the code that begins with "x") ?

why did the last line get the correct output, and the others didn't?

When you print foo, what gets printed out is str(foo).

However, if foo is a liststr(foo) uses repr(bar) for each element bar, not str(bar).

The str of a string is the string itself; the repr of a string is the string inside quotes, and escaped.

how do I correct the wrong ones

If you want to print the str of every element in a list, you have to do that explicitly. For example:

print '[' + ', '.join(["asdf", "中文"]) + ']'


解决办法2:
#coding: utf-8

import json

class CCode:
    def str(self, content, encoding='utf-8'):
        # 只支持json格式
        # indent 表示缩进空格数
        return json.dumps(content, encoding=encoding, ensure_ascii=False, indent=4)
        pass

    pass

if __name__ == "__main__":
    dictData = {"语文" : 99, "数学" : 100, "英语" : 98}
    listData = ["语文", "数学", "英语"]

    cCode = CCode()

    print cCode.str(dictData)
    print cCode.str(listData)


参考链接:
https://my.oschina.net/leejun2005/blog/74430

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值