Python print() 输出差异
我正在摆弄 python,遵循本教程:
http://en .wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_3/Hello,_World
根据它,我的以下代码的输出:
print("Single String")
print("Concat", "String")
应该看起来像这样:
Single String
Concat String
但它看起来像这样:
Single String
('Concat', 'String')
这是为什么?我在 OSX 上使用 Python 2.6。
编辑:我刚刚意识到该指南适用于 3.0,而我有 2.6。这是导致问题的原因吗?升级 Python 安装的最快方法是什么?
编辑2:升级修复了它:)接受的答案解释了差异。
I'm messing around with python, following this tutorial:
http://en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_3/Hello,_World
According to it, my output for the following code:
print("Single String")
print("Concat", "String")
Should look like this:
Single String
Concat String
But it looks like this:
Single String
('Concat', 'String')
Why is this? I'm on OSX with Python 2.6.
EDIT: I just realized the guide is for 3.0, and I have 2.6. Is that causing the issue? What is the quickest way to upgrade my Python install?
EDIT 2: An upgrade fixed it :) Accepted answer explains the differences.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
这是一个元组。当您放置
,
时,它会变成 元组< /a> 因此 Python 以同样的方式输出它。元组由多个用逗号分隔的值组成。
This is a
tuple
. When you put the,
it becomes a tuple and hence Python outputs it the same way.A tuple consists of a number of values separated by commas.
不是对OP最初问题的回答,我认为sukhbir回答得很好,而是对后续问题的回答。
我相信最快的升级方法是转到Python 网站 并下载 v3。
Not an answer to the OP's original question, which I think sukhbir answered quite well, but to the follow up question.
I believe the quickest way to upgrade would be to go to the Python website and download v3.
如果您使用的是 Python 2.x,则可以使用
Python 3.x 更改 print 的工作方式,以前它是一个语句,现在它是一个函数。
If you are using Python 2.x you can just use
Python 3.x changes the way print works, previously it was a statement and now it is a function.
为了兼容
Python 2.7
,您可以使用占位符For compatibility in
Python 2.7
you can use placeholders原因是您正在使用 Python 2 运行 Python 3 教程。
The reason is that you are running a Python 3 tutorial with Python 2.
在 Python 2.6 中,您也可以说
获取 3.x 语法。
In Python 2.6 you can also say
to get the 3.x syntax.
为了获得您想要的行为,您需要打印元组的字符串表示形式。您可以通过对字符串使用
join
方法来获得此结果:行为不符合预期的原因是在 Python 2 中,
print
是一个关键字。在Python 3中,它已被函数(也称为print
)取代,因此后一种语法调用函数而不是打印元组。 来复制在 Python 3 中看到的行为。您可以使用一组用于函数调用的括号和一组用于元组的括号
To get the behaviour you want, you need to print a string representation of the tuple. You can get this by using the
join
method on strings:The reason the behaviour is not as expected is that in Python 2,
print
is a keyword. In Python 3, it has been replaced by a function (alsoprint
), so the latter syntax calls the function instead of printing a tuple. You can replicate the behaviour you have see in Python 3 withOne set of parentheses for the function call, and one for the tuple.