如何在打印声明后抑制换行符?

Ci3*_*Ci3 52 python python-3.x

我读到在打印语句后禁止换行,你可以在文本后面加一个逗号.这里的示例看起来像Python 2. 如何在Python 3中完成?

例如:

for item in [1,2,3,4]:
    print(item, " ")
Run Code Online (Sandbox Code Playgroud)

需要更改哪些内容才能将它们打印在同一行上?

Lev*_*von 92

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

在Python 3.x中使用此构造:

for item in [1,2,3,4]:
    print(item, " ", end="")
Run Code Online (Sandbox Code Playgroud)

这将产生:

1  2  3  4
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请参阅此Python文档:

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

-

除了:

此外,该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
Run Code Online (Sandbox Code Playgroud)

  • 完善!所以end =""只是覆盖了换行符. (3认同)
  • 更具体地说,它来自__future__ import print_function`. (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")
Run Code Online (Sandbox Code Playgroud)

输出量

>>>
This first text and second text will be on the same line
Unlike this text which will be on a newline
Run Code Online (Sandbox Code Playgroud)


归档时间:

查看次数:

92455 次

最近记录:

8 年,5 月 前