本文介紹了在 Python 中將變量的每一項打印在單獨的行上的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我正在嘗試在 Python 中打印一個包含數字的列表,并且當它打印列表中的項目時,所有項目都打印在同一行.
I am trying to print a list in Python that contains digits and when it prints the items in the list all print on the same line.
print ("{} ".format(ports))
這是我的輸出
[60, 89, 200]
我怎樣才能看到這種形式的結果:
how can I see the result in this form:
60
89
200
我試過 print ("
".join(ports))
但這不起作用.
I have tried print ("
".join(ports))
but that does not work.
推薦答案
遍歷列表并在新行打印每個項目:
Loop over the list and print each item on a new line:
for port in ports:
print(port)
或在加入之前將整數轉換為字符串:
or convert your integers to strings before joining:
print('
'.join(map(str, ports)))
或告訴 print()
使用換行符作為分隔符,并使用 *
splat 語法將列表作為單獨的參數傳遞:
or tell print()
to use newlines as separators and pass in the list as separate arguments with the *
splat syntax:
print(*ports, sep='
')
演示:
>>> ports = [60, 89, 200]
>>> for port in ports:
... print(port)
...
60
89
200
>>> print('
'.join(map(str, ports)))
60
89
200
>>> print(*ports, sep='
')
60
89
200
這篇關于在 Python 中將變量的每一項打印在單獨的行上的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!