为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Cats萌萌 2019-11-15 13:18:32
我读到这是为了在打印语句后取消换行符,您可以在文本后加上逗号。这里的示例看起来像Python2。如何在Python 3中完成呢?例如:for item in [1,2,3,4]:    print(item, " ")需要更改什么以便将它们打印在同一行上?
查看完整描述

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


查看完整回答
反对 回复 2019-11-15
?
慕莱坞森

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


查看完整回答
反对 回复 2019-11-15
?
守着星空守着你

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)

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


查看完整回答
反对 回复 2019-11-15
  • 3 回答
  • 0 关注
  • 532 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信