更新时间:2023-11-27 20:47:58
为什么最后一行得到正确的输出,而其他没有?
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.