打印声明后如何取消换行符?

我读到这是为了在打印语句后取消换行符,您可以在文本后加上逗号。这里的示例看起来像Python2。如何在Python 3中完成呢?


例如:


for item in [1,2,3,4]:

    print(item, " ")

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


Cats萌萌
浏览 538回答 3
3回答

米琪卡哇伊

问题问:“ 如何在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 newlineNew: print(x, end=" ")  # Appends a space instead of a newline-除了:此外,该print()功能还提供了sep一个参数,可让您指定应如何分隔要打印的单个项目。例如,In [21]: print('this','is', 'a', 'test')  # default single space between itemsthis is a testIn [22]: print('this','is', 'a', 'test', sep="") # no spaces between itemsthisisatestIn [22]: print('this','is', 'a', 'test', sep="--*--") # user specified separationthis--*--is--*--a--*--test

慕莱坞森

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 lineUnlike this text which will be on a newline

守着星空守着你

因为python 3 print()函数允许end =“”定义,所以可以满足大多数问题。就我而言,我想使用PrettyPrint并感到沮丧,因为该模块未进行类似的更新。所以我做到了我想要的:from pprint import PrettyPrinterclass 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)我得到了我想要的(代替您想要的-您的里程可能会有所不同)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python