[英]Print output in a single line
我有以下代碼:
>>> x = 0
>>> y = 3
>>> while x < y:
... print '{0} / {1}, '.format(x+1, y)
... x += 1
輸出:
1 / 3,
2 / 3,
3 / 3,
我希望我的輸出像:
1 / 3, 2 / 3, 3 / 3
我搜索並發現在一行中執行此操作的方法是:
sys.stdout.write('{0} / {1}, '.format(x+1, y))
還有另一種方法嗎? 我對sys.stdout.write()
感到不舒服,因為我不知道它與print
有什么不同。
您可以使用
打印“東西”,
(使用尾隨逗號,不插入換行符),所以試試這個
... print '{0} / {1}, '.format(x+1, y), #<= with a ,
我認為sys.stdout.write()
會很好,但是Python 2中的標准方法是使用尾隨逗號print
,正如mb14建議的那樣。 如果您使用的是Python 2.6+並希望向上兼容Python 3,則可以使用新的print
函數 ,該函數提供更易讀的語法:
from __future__ import print_function
print("Hello World", end="")
不需要write
。
如果你在print語句后面加上一個逗號,你就會得到你需要的東西。
注意事項:
>>> while x < y:
... print '{0} / {1}, '.format(x+1, y),
... x += 1
...
1 / 3, 2 / 3, 3 / 3,
注意附加的逗號。
這是一種使用itertools實現您想要的方法。 對於打印成為函數的Python3,這也適用
from itertools import count, takewhile
y=3
print(", ".join("{0} / {1}".format(x,y) for x in takewhile(lambda x: x<=y,count(1))))
您可能會發現以下方法更容易遵循
y=3
items_to_print = []
for x in range(y):
items_to_print.append("{0} / {1}".format(x+1, y))
print(", ".join(items_to_print))
使用帶有逗號的逗號print
的問題是,最后會得到一個額外的逗號,並且沒有換行符。 這也意味着你必須有單獨的代碼才能與python3向前兼容
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.