如何在print语句后抑制换行?

68
我读到了一个关于如何取消 print 语句在输出后自动换行的问题,可以在文本后加上逗号。这个 例子 是针对 Python 2 的。那么在 Python 3 中应该怎么做呢? 举个例子:
for item in [1,2,3,4]:
    print(item, " ")

需要进行什么更改才能将它们打印在同一行上?


1
你可以直接执行 print(' '.join([str(i) for i in [1, 2, 3, 4]])) - anon582847382
1
print(*[1, 2, 3, 4])适用于打印以空格分隔的序列的常见情况。 - John La Rooy
1
相关帖子 - 如何在不换行或空格的情况下打印?。该主题中被接受的答案涵盖了所有Python版本。 - RBT
5个回答

110

这个问题问道:"如何在Python 3中完成?"

使用以下结构与Python 3.x:

for item in [1,2,3,4]:
    print(item, " ", end="")

这将生成:

1  2  3  4

请参考这个Python文档以获取更多信息:

Old: print x,           # Trailing comma suppresses newline
New: print(x, end=" ")  # Appends a space instead of a newline

--

另外一件事:

除此之外,print() 函数还提供了 sep 参数,让你可以指定如何分隔要打印出来的各个项。例如:

In [21]: print('this','is', 'a', 'test')  # default single space between items
this is a test

In [22]: print('this','is', 'a', 'test', sep="") # no spaces between items
thisisatest

In [22]: print('this','is', 'a', 'test', sep="--*--") # user specified separation
this--*--is--*--a--*--test

3
太好了!所以 end="" 只是覆盖了换行符。 - Ci3
无论我看哪里,每个人都说要使用 end='',但我却遇到了 SyntaxError: invalid syntax 错误。 - thang
@thang 你使用的是哪个版本的Python?这适用于3.x版本。 - Levon
@thang 你可能想要查看 "from future import print",不确定它是否能解决你的问题,但这很有可能。http://python-future.org/quickstart.html 和 https://dev59.com/9Gw05IYBdhLWcg3wuT8L - Levon
3
更具体地说,它是 from __future__ import print_function - Scott Stafford
显示剩余3条评论

5

Python 3.6.1的代码

print("This first text and " , end="")

print("second text will be on the same line")

print("Unlike this text which will be on a newline")

输出

>>>
This first text and second text will be on the same line
Unlike this text which will be on a newline

1
这解释了end=""参数将如何影响下一行,但不是其后面的那一行 - 谢谢! - Paulo Raposo

4

直到Python 3.0,print语句才转变为函数。如果您使用的是较旧版本的Python,则可以通过在末尾加上逗号来抑制换行,例如:

print "Foo %10s bar" % baz,

5
这个问题特别询问使用Python 3。 - Josh Wright

0
因为Python 3的print()函数允许定义end="",这满足了大多数问题。
在我的情况下,我想要PrettyPrint,但很失望这个模块没有类似的更新。所以我让它做我想要的事情:
from pprint import PrettyPrinter

class CommaEndingPrettyPrinter(PrettyPrinter):
    def pprint(self, object):
        self._format(object, self._stream, 0, 0, {}, 0)
        # this is where to tell it what you want instead of the default "\n"
        self._stream.write(",\n")

def comma_ending_prettyprint(object, stream=None, indent=1, width=80, depth=None):
    """Pretty-print a Python object to a stream [default is sys.stdout] with a comma at the end."""
    printer = CommaEndingPrettyPrinter(
        stream=stream, indent=indent, width=width, depth=depth)
    printer.pprint(object)

现在,当我执行:

comma_ending_prettyprint(row, stream=outfile)

我得到了我想要的(替换成你想要的 -- 你的结果可能会有所不同)


0

关于不换行打印的信息可以在这里找到。

在Python 3.x中,我们可以在print函数中使用'end='。这告诉它以我们选择的字符结束字符串,而不是以换行符结束。例如:

print("My 1st String", end=","); print ("My 2nd String.")

这会导致:

My 1st String, My 2nd String.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接