用Python打印包含中文字符的列表

2024-05-17 00:35:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我的代码看起来像:

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

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

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

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

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

我的第二个问题是:如何纠正错误的字符(使它们输出真实字符而不是以“x”开头的代码)?

谢谢你们!!


Tags: 代码字符utfprinteclipsecodingasdfxe6
2条回答

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

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

然而,如果foolist,则str(foo)对每个元素bar使用repr(bar),而不是str(bar)

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

how do I correct the wrong ones

如果要打印list中每个元素的str,必须显式地执行该操作。例如:

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

已经有零星的建议来改变这种行为,所以对序列调用其成员的strPEP 3140是被拒绝的建议。This thread from 2009解释了拒绝它背后的设计原理。

但最主要的是,这两种方法不会打印相同的东西:

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

或者,改写一下Batchelder的话:repr总是给极客的;str在可能的情况下是给人类的,但是打印带有括号和逗号的列表已经是给极客的了。

前两个使用的是字符串的__repr__,最后一个使用的是__str__方法

你可以用

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

相关问题 更多 >