Python 新行:如何在不换行的情况下打印 Python
⚡ 智能摘要
Python print() 函数默认会添加一个换行符,但你可以避免这种情况。这里你将学习 end 参数。 Python 使用 2 个逗号、sys.stdout.write() 和循环将输出保持在一行上。

Python print() 内置函数用于在命令提示符中打印给定的内容。 Python print 是在末尾添加了一个换行符。
正常 print() 函数的工作原理
print() 函数用于在命令提示符或控制台中显示内容。
下面是一个展示如何工作的示例 Python 打印时不使用换行符功能。
print("Hello World") print("Welcome to Guru99 Tutorials")
输出:
Hello World Welcome to Guru99 Tutorials
In the given output, you can see that the strings that we have given in print() are displayed on separate lines. The string "Hello World " is printed first, and "Welcome to Guru99 Tutorials" is printed on the next line.
如何在不换行的情况下打印 Python?
从 Python 3+ 版中,print() 新增了一个参数,名为 end=。此参数负责删除 print() 中默认添加的换行符。
在 Python 3 打印时不换行例如下面,我们希望字符串在同一行打印 Python. To get that working just add end="" inside print() as shown in the example below:
print("Hello World ", end="") print("Welcome to Guru99 Tutorials")
输出:
Hello World Welcome to Guru99 Tutorials
我们得到了想要的输出结果,但是字符串之间没有空格。字符串“Hello World”和“Welcome to” Guru99篇教程全部印在一起,没有留白。
In order to add space or special character or even string to be printed, the same can be given to the end="" argument, as shown in the example below.
print("Hello World ", end=" ") print("Welcome to Guru99 Tutorials")
So I here we have added one space to the end argument, for example (end=" "). Now, if you see the output, you should see a space between Hello World and Welcome to Guru99教程。
输出:
Hello World Welcome to Guru99 Tutorials
It's not only space that you can give to the end argument, but you can also specify a string you wish to print between the given strings. So here is an example of it
print("Hello World ", end="It's a nice day! ") print("Welcome to Guru99 Tutorials")
输出:
Hello, World It's a nice day! Welcome to Guru99 Tutorials
不打印换行符 Python 2.x
为了使打印的字符串不带换行符,在 python2.x 中,您必须在打印语句末尾添加逗号 (,),如下所示:
print "Hello World ", print "Welcome to Guru99 Tutorials."
输出:
Hello World Welcome to Guru99 Tutorials
运用 Python 系统模块
还有一种方法可以用来打印而不换行 Python 内置模块名为 系统.
这是一个工作示例,展示了如何使用 系统 不带换行符打印的模块 Python 字符串。
要使用 sys 模块,首先导入该模块 系统 使用 进口 关键字。接下来,利用 stdout.write() 方法 系统 模块,打印你的字符串。
import sys sys.stdout.write("Hello World ") sys.stdout.write("Welcome to Guru99 Tutorials")
输出:
Hello World Welcome to Guru99 Tutorials
使用 print() 打印不带换行符的列表
Consider a list of items for example: mylist = ["PHP", JAVA", "C++", "C", "PHYTHON"] and you want to print the values inside the list using 循环。因此,这里您可以使用 print() 来显示列表内的值,如下例所示:
mylist = ["PHP", "JAVA", "C++", "C", "PHYTHON"] for i in mylist: print(i)
输出:
PHP JAVA C++ C PHYTHON
输出显示列表项,每个项都依次打印在新行上。如果您希望列表中的所有项目都在同一行中,该怎么办?为此,请在 print() 中使用 end 参数,它将删除 Python 并在同一行打印列表的所有项目。
mylist = ["PHP", "JAVA", "C++", "C", "PYTHON"] for i in mylist: print(i, end=" ")
输出:
PHP JAVA C++ C PHYTHON
打印星号(*)图案,不带换行符和空格
的例子 Python 不带换行符的打印将使用 print()函数 使用 for 循环在同一行打印星号(*)。
for i in range(0, 20): print('*', end="")
输出:
********************
