如何在Python中不使用换行符进行打印?
通常,从 C/C++ 切换到Python的人们想知道如何打印两个或多个变量或语句,而无需在Python中换行。由于默认情况下Python print()函数以换行符结尾。如果您使用 print(a_variable), Python有一个预定义的格式,那么它将自动转到下一行。
例如:
Python3
print("geeks")
print("geeksforgeeks")
python
# Python 2 code for printing
# on the same line printing
# geeks and geeksforgeeks
# in the same line
print("geeks"),
print("geeksforgeeks")
# array
a = [1, 2, 3, 4]
# printing a element in same
# line
for i in range(4):
print(a[i]),
python3
# Python 3 code for printing
# on the same line printing
# geeks and geeksforgeeks
# in the same line
print("geeks", end =" ")
print("geeksforgeeks")
# array
a = [1, 2, 3, 4]
# printing a element in same
# line
for i in range(4):
print(a[i], end =" ")
Python3
# 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)
#This code is contributed by anuragsingh1022
将导致:
geeks
geeksforgeeks
但有时可能会发生我们不想转到下一行但想在同一行打印的情况。那么我们能做些什么呢?
例如:
Input : print("geeks") print("geeksforgeeks")
Output : geeks geeksforgeeks
Input : a = [1, 2, 3, 4]
Output : 1 2 3 4
这里讨论的解决方案完全取决于您使用的Python版本。
在Python 2.x 中不带换行符打印
Python
# Python 2 code for printing
# on the same line printing
# geeks and geeksforgeeks
# in the same line
print("geeks"),
print("geeksforgeeks")
# array
a = [1, 2, 3, 4]
# printing a element in same
# line
for i in range(4):
print(a[i]),
输出:
geeks geeksforgeeks
1 2 3 4
在Python 3.x 中不使用换行符打印
蟒蛇3
# Python 3 code for printing
# on the same line printing
# geeks and geeksforgeeks
# in the same line
print("geeks", end =" ")
print("geeksforgeeks")
# array
a = [1, 2, 3, 4]
# printing a element in same
# line
for i in range(4):
print(a[i], end =" ")
输出:
geeks geeksforgeeks
1 2 3 4
在Python 3.x 中不使用换行符打印而不使用 for 循环
Python3
# 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)
#This code is contributed by anuragsingh1022
输出:
1 2 3 4 5 6