Python 以单行打印输出

Python 以单行打印输出,python,printing,Python,Printing,我有以下代码: >>> x = 0 >>> y = 3 >>> while x < y: ... print '{0} / {1}, '.format(x+1, y) ... x += 1 我希望我的输出像: 1 / 3, 2 / 3, 3 / 3 我搜索发现,在一行中实现这一点的方法是: sys.stdout.write('{0} / {1}, '.format(x+1, y)) 还有别的方法吗?我对sys.s

我有以下代码:

>>> x = 0
>>> y = 3
>>> while x < y:
    ... print '{0} / {1}, '.format(x+1, y)
    ... x += 1
我希望我的输出像:

1 / 3, 2 / 3, 3 / 3 
我搜索发现,在一行中实现这一点的方法是:

sys.stdout.write('{0} / {1}, '.format(x+1, y))
还有别的方法吗?我对
sys.stdout.write()
感到不舒服,因为我不知道它与您可以使用的
print
有什么不同

打印“某物”

(带尾随逗号,不插入换行符),因此 试试这个


。。。打印“{0}/{1}.”格式(x+1,y),#无需
写入

如果在print语句后面加一个逗号,就可以得到所需的内容

注意事项:

  • 如果希望下一个文本在新行上继续,则需要在末尾添加空白打印语句
  • 在Python3.x中可能会有所不同
  • 将始终至少添加一个空格作为分隔符。在这种情况下,这是可以的,因为你想要一个空间来分隔它
    • >>而x

      请注意附加的逗号。

      我认为
      sys.stdout.write()
      可以,但是Python 2中的标准方法是
      print
      带有尾随逗号,正如mb14所建议的那样。如果您使用的是Python 2.6+,并且希望向上兼容Python 3,则可以使用新的
      print
      函数,该函数提供了更可读的语法:

      from __future__ import print_function
      print("Hello World", end="")
      

      您可以在打印结束语句中使用
      <代码>
      
      while x<y:
          print '{0} / {1}, '.format(x+1, y) ,
          x += 1
      

      而这里有一种使用itertools实现您想要的功能的方法。这对于Python3也可以,在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))))
      

      使用带有尾随逗号的
      print
      的问题是,在末尾有一个额外的逗号,并且没有换行符。这还意味着您必须有单独的代码才能与python3向前兼容。谢谢我把逗号放进去了。我没有使用
      itertools
      的经验,但我打算好好读一读。谢谢你。
      from __future__ import print_function
      print("Hello World", end="")
      
      
      while x<y:
          print '{0} / {1}, '.format(x+1, y) ,
          x += 1
      
      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))