3 回答

TA贡献1998条经验 获得超6个赞
问题问:“ 如何在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

TA贡献1810条经验 获得超4个赞
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

TA贡献1799条经验 获得超8个赞
因为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)
我得到了我想要的(代替您想要的-您的里程可能会有所不同)
添加回答
举报