攜手創作,共同成長!這是我參與「掘金日新計劃 · 8 月更文挑戰」的第 7 天,點擊查看活動詳情
通常,從 C/C++ 切換到 Python of people want to know how to print two or more variables or statements,而無需在 Python 中換行.由於默認情況下python print() The function ends with a newline.如果您使用 print(a_variable),Python There is a predefined format,then it will automatically轉到下一行.
例如:
print("py")
print("python")
復制代碼
The above code will result in a newline:
py
python
復制代碼
But sometimes it can happen that we don't want to go to the next line but want to print on the same line.那麼我們應該怎麼做呢?
例如:
輸入: print("haiyong")print(".site")
輸出:haiyong.site
輸入:a = [1, 2, 3, 4]
輸出:1 2 3 4
復制代碼
The solutions discussed here depend on what you use python 版本.
# for printing on the same line Python 2 代碼
# 在同一行打印 hy 和 haiyong
print("hy"),
print("haiyong")
# 數組
a = [1, 2, 3, 4]
# Print elements on the same line
for i in range(4):
print(a[i]),
復制代碼
輸出:
hy haiyong
1 2 3 4
復制代碼
# for printing on the same line Python 3 代碼
# hy 和 haiyong 在同一行
print("hy", end =" ")
print("haiyong")
# 數組
a = [1, 2, 3, 4]
# Print elements on the same line
for i in range(4):
print(a[i], end =" ")
復制代碼
輸出:
hy haiyong
1 2 3 4
復制代碼
# 在 Python 3.x is printed without a newline character in for 循環
l=[1,2,3,4,5,6]
# 使用 * Notation prints list elements in one line
print(*l)
#This code is contributed by haiyong
復制代碼
輸出:
1 2 3 4 5 6
復制代碼
本篇文章到此就結束了,相關文章:
感謝大家的閱讀,有什麼問題的話可以在評論中告訴我.希望大家能夠給我來個點贊+收藏+評論 ,你的支持是海海更新的動力!後面我會持續分享前端 & 後端相關的專業知識.