【发布时间】:2026-02-07 06:35:01
【问题描述】:
在 python 2.7 中
print("hello\nJoonho")
打印
“你好
俊昊
但是
a=3
print(a, "\nhello\nJoonho")
打印
"(3, "\n你好\n俊浩")
您能解释一下为什么会这样吗? “print()”不是函数吗? 以及如何绕过这个问题?
【问题讨论】:
标签: python-2.7 printing newline
在 python 2.7 中
print("hello\nJoonho")
打印
“你好
俊昊
但是
a=3
print(a, "\nhello\nJoonho")
打印
"(3, "\n你好\n俊浩")
您能解释一下为什么会这样吗? “print()”不是函数吗? 以及如何绕过这个问题?
【问题讨论】:
标签: python-2.7 printing newline
print 始终为您提供在标准输出上打印的对象的可打印表示。当您说print(a, "\nhello\nJoonho") 时,这里的(a, "\nhello\nJoonho") 是一个元组,因此表示为元组对象。
为了更清楚地了解这一点:
如果你这样做print(a, "\nhello\nJoonho")[1],那么它实际上会打印为
>>> print(0, '\nhello\nJoonho')[1]
hello
Joonho
因为 [1] 表示的对象是一个字符串,\n 被转换为字符串对象的 stdout 上的换行符。
【讨论】:
[1] 很好!
在 python 3 之前 print 不是一个函数。在 python 3 中 print 是一个函数。
你可以翻译python 2.7
print(a, "\nhello\nJoonho")
到python 3
print((a, "\nhello\nJoonho"))
所以你的语句实际上打印了元组的表示。
这是因为当您将字符串传递给打印函数时,它会按原样打印。如果您将任何其他内容传递给 print 函数,例如一个元组,它的表示就会被打印出来。您还可以使用repr 函数获取对象的表示形式:
>>> repr((a, "\nhello\nJoonho"))
"(3, '\\nhello\\nJoonho')"
对象的表示通常是一个有效的python表达式。
【讨论】:
在 Python 2 中,print is a statement。因此,通过调用print(a, "\nhello\nJoonho"),您正在打印元组(a, "\nhello\nJoonho")。
您可以在 Python 2 中通过从未来导入 print() 函数来使用它:
from __future__ import print_function
打印语句在打印之前将对象转换为字符串:
因此,在print ("hello\nJoonho") 中,对象("hello\Joonho") 将被转换为字符串(("hello\nJoonho").__str__(),结果为'hello\nJoonho')。然后,将打印字符串'hello\nJoonho'。
在print (a, "\nhello\nJoonho") 中,(a, "\nhello\nJoonho") 将被转换为字符串((a, "\nhello\nJoonho").__str__(),其结果为"(3, '\\nhello\\nJoonho')")。然后,将打印字符串"(3, '\\nhello\\nJoonho')"。请注意,当第二个元组转换为字符串时,\n 会被转义。
【讨论】:
print函数/语句(取决于python的版本)有两种操作方式。当传递一个字符串时,它直接将其写入标准输出。当传递任何其他内容时,它将其表示写入标准输出。对象的表示是一个有效的python表达式,例如:repr("\nhello\nJoonho")是字符串'\nhello\nJoonho'
repr("\nhello\nJoonho") 计算结果为"'\\nhello\\nJoonho'",它被转义了,所以我不确定print 是否使用它。在 PyPy 实现中,他们使用 str() 转换为字符串:bitbucket.org/pypy/pypy/src/… 我不确定 CPython,但根据经验,他们似乎使用类似于 str() 的东西(我们需要检查源代码)。跨度>