在Python中打印包含中文字符的列表 [英] Print a list that contains Chinese characters in Python

查看:634
本文介绍了在Python中打印包含中文字符的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码如下:

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

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

Eclipse控制台中的输出非常奇怪:

The output in the Eclipse console is very strange:

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

我的第一个问题是:为什么最后一行得到正确的输出,没有?

我的第二个问题是:如何更正错误的而不是以x开头的代码)

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?

当你 print foo 时,打印出来的是 str(foo)

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

但是,如果 foo 列表 str(foo)对每个元素使用 repr(bar) bar ,而不是 str(bar)

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

str 一个字符串是字符串本身; repr 是引号内的字符串,并且转义。

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


如果您要打印 str ,请更正错误的


$ b < list 中的每个元素,你必须明确这样做。例如:

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

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






有零星的建议因此在序列上的 str 在其成员上调用 str PEP 3140 是被拒绝的提案。 2009年的这个帖子解释了拒绝它的设计原理。


There have been sporadic proposals to change this behavior, so str on a sequence calls str on its members. PEP 3140 is the rejected proposal. This thread from 2009 explains the design rationale behind rejecting it.

但主要是因为这些不打印相同的东西:

But primarily, it's either so these don't print the same thing:

a = 'foo, bar'
b = 'foo'
c = 'bar'
print [a]
print [b, c]

或者,改写Ned Batchelder: repr str 适用于人类,但是使用括号和逗号打印列表已经是极客了。

Or, paraphrasing Ned Batchelder: repr is always for geeks; str is for humans when possible, but printing lists with their brackets and commas is already for geeks.

这篇关于在Python中打印包含中文字符的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆