是否可以在Python 2中使用'print >>'而不使用换行符和空格?

Enz*_*ura 2 python python-2.x python-2.7

在以下代码中:

with open("output", "w") as f:
    print >> f, "foo"
    print >> f, "bar"
Run Code Online (Sandbox Code Playgroud)

'output'文件将是:

foo
bar
Run Code Online (Sandbox Code Playgroud)

如何避免使用换行符和空格print >>

PS:我其实想知道是否可以使用它print >>.我知道其他方法可以避免'\n',例如f.write("foo")f.write("bar").

另外,我知道尾随的逗号.但那打印foo bar,而不是foobar.

Ry-*_*Ry- 5

一个尾随的逗号使print语句变得神奇,就像不打印换行符,除非没有进一步的输出(没有记录!):

print >>f, "foo",
Run Code Online (Sandbox Code Playgroud)

但如果您想要一致的无换行策略(并且因为您有第二个print,它将打印一个空格),这并不是真的有用.为此,使用Python 3的打印功能:

from __future__ import print_function
Run Code Online (Sandbox Code Playgroud)

print("foo", end="", file=f)
Run Code Online (Sandbox Code Playgroud)