一般来说,从C/C++切换到 Python 的人想知道如何打印两个或多个变量或语句而不切换到 python 中的换行符。因为 python print() 函数默认以换行符结尾。如果你使用 print(a_variable) Python 有一个预定义的格式,它会自动转到下一行。
例如:
print("cafedev")
print("cafedevscafedev")
输出
cafedev
cafedevscafedev
但有时可能会发生我们不想转到下一行而是想在同一行打印的情况。所以,我们能做些什么?
例如:
Input : print("cafe") print("cafedev")
Output : cafe cafedev
Input : a = [1, 2, 3, 4]
Output : 1 2 3 4
这里讨论的解决方案完全取决于您使用的 python 版本。
在 Python 2.x 中打印时不换行
# Python 2 code for printing
# on the same line printing
# cafe and cafedev
# in the same line
print("cafe"),
print("cafedev")
# array
a = [1, 2, 3, 4]
# printing a element in same
# line
for i in range(4):
print(a[i]),
输出
cafe cafedev
1 2 3 4
在 Python 3.x 中打印时不换行
# Python 3 code for printing
# on the same line printing
# geeks and cafedev
# in the same line
print("cafe", end =" ")
print("cafedev")
# array
a = [1, 2, 3, 4]
# printing a element in same
# line
for i in range(4):
print(a[i], end =" ")
输出
-->cafe cafedev
1 2 3 4
使用循环在 Python 3.x 中打印无换行符
# Print without newline in Python 3.x without using for loop
l=[1,2,3,4,5,6]
# using * symbol prints the list
# elements in a single line
print(*l)
标签:cafe,Python,打印,same,换行,print,line,cafedev
From: https://www.cnblogs.com/xiudiu/p/tu-hoc-python-lam-the-nao-de-in-ma-khong-co-dong-moi-tron