print 如何准确处理逗号?

How does print handle the comma exactly?

本来我以为:

print "text",

差不多
sys.stdout.write("text" + " ")

但后来我尝试了以下操作:

print '(',
sys.stdout.write("text")
print ')'

预期输出:

( text)

(text )  # if the space is added by the next print statement

我得到了什么:

(text)  # no space at all

谁能解释一下这种行为?我只是好奇

打印包括将项目转换为字符串,然后将它们写入文件对象(默认情况下为 sys.stdout)。在 Python 2 中,print 语句在您写入的文件对象上保留一个标志,称为 soft space 标志 。参见Python C API中的file.softspace attribute and the PyFile_SoftSpace() function

此标志用于跟踪何时写入 space。打印在内部实现为一系列 PRINT_ opcodes,那些管理标志:

  • 打印一个item(with PRINT_ITEM or PRINT_ITEM_TO)首先检查flag,如果设置了就写一个space,写完item后会设置flag再次
  • 写入换行符是一个单独的操作码(PRINT_NEWLINEPRINT_NEWLINE_TO),并且在不写入 space.
  • 的情况下清除标志

但是,直接写入文件对象,就像您对sys.stdout.write()所做的那样,清除该标志(在执行写入之前):

>>> import sys
>>> if True:
...     sys.stdout.softspace = 1
...     sys.stdout.write('{}\n'.format(sys.stdout.softspace))
...     sys.stdout.softspace
...
1
0

(我使用了 if 块来防止解释器循环在其间写入提示)。

这就是您的示例中发生的情况:

  • ( 写入 sys.stdout 并设置 sys.stdout.softspace
  • sys.stdout.write('text') 再次清除标志并写出text
  • 在写)之前,PRINT_ITEM检查flag,发现没有设置,就写)。再次立旗。
  • PRINT_NEWLINE写了一个换行符,再次清除标志。

跟踪一个简单的功能需要做大量工作,这也是 Python 3 移至 函数 进行打印的原因之一。参见 PEP 3105