Python 2.7:print()对其中的字符串做了什么

All*_*ack 0 python string python-2.7 python-3.x

我一直在使用print()python 2.7文件中的语法,尽管我知道在2.7中print是一个语句,而不是像3.X中那样的函数.但是python解释器似乎没有任何print()语法问题,所以我保持它可以使3.X的未来端口更容易.但是我注意到Python在处理括号内字符串文字的方式上有些可疑:

>>>> print("\nFirst line\n", "Second line")

('\First line\n', 'Second line')  
Run Code Online (Sandbox Code Playgroud)

而典型的2.7语句语法按预期打印换行符:

>>>>print "\nFirst line\n", "Second line"

First line
Second line
Run Code Online (Sandbox Code Playgroud)

题:

那么print()在2.7中工作的原因是什么,但忽略了这个\n角色?它几乎就像print()打印出__repr__包含的字符串文字的字符串.

kin*_*all 5

您可以使用括号括起任何表达式而不更改其值,因此:

print ("hello world")
Run Code Online (Sandbox Code Playgroud)

与以下内容完全相同:

print "hello world"
Run Code Online (Sandbox Code Playgroud)

看起来像一个函数调用乍一看,但实际上你只是打印一个恰好在括号中的字符串表达式.同样的交易:

x = 1 + 2   # same as
x = (1 + 2)
Run Code Online (Sandbox Code Playgroud)

但是,如果您尝试打印多个项目,或者在字符串末尾使用逗号打印(通常用于避免打印换行符),您将获得您所描述的结果类型:

print ("hello", "world")
print ("hello world",)
Run Code Online (Sandbox Code Playgroud)

在这种情况下,您正在打印元组.

t = ("hello", "world")   # or
t = ("hello world", )

print t
Run Code Online (Sandbox Code Playgroud)

并且打印元组实际上打印出其中repr()的每个项目.