关于python:如何在打印语句后抑制换行符?

How can I suppress the newline after a print statement?

我读到这篇文章是为了在print语句后禁止换行,您可以在文本后加一个逗号。这里的示例类似于python 2。如何在python 3中完成?

例如:

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

需要更改什么以便在同一行上打印它们?


问题是:"如何在Python3中完成?"

在python 3.x中使用此结构:

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

这将产生:

1
1  2  3  4

有关详细信息,请参阅此python文档:

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

——

旁白:

此外,print()函数还提供sep参数,该参数允许您指定要打印的各个项目应如何分开。例如。,

1
2
3
4
5
6
7
8
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


直到python 3.0,print才从语句转换到函数。如果您使用的是旧的python,那么您可以用一个尾随逗号来禁止换行,如下所示:

1
print"Foo %10s bar" % baz,


python 3.6.1代码

1
2
3
4
5
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")

产量

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


因为python 3 print()函数允许end="definition,这可以满足大多数问题。

在我的例子中,我想预打印,但对于这个模块没有进行类似的更新感到很沮丧。所以我让它做我想做的:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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"
"
        self._stream.write("
,
")

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)

现在,当我这样做:

1
comma_ending_prettyprint(row, stream=outfile)

我得到了我想要的(代替你想要的——你的里程可能会有所不同)