簡體   English   中英

以單行打印輸出

[英]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語句后面加上一個逗號,你就會得到你需要的東西。

注意事項:

  • 如果希望下一個文本在新行上繼續,則需要在末尾添加空白打印語句。
  • 在Python 3.x中可能有所不同
  • 將始終至少添加一個空格作為分隔符。 在這種情況下,這沒關系,因為無論如何你想要一個分隔它的空間。
>>> while x < y:
...     print '{0} / {1}, '.format(x+1, y),
...     x += 1
... 
1 / 3,  2 / 3,  3 / 3, 

注意附加的逗號。

您可以使用,在打印語句的結束。


while x<y:
    print '{0} / {1}, '.format(x+1, y) ,
    x += 1
你可以進一步閱讀這個

這是一種使用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM