在一行中打印输出

6 投票
6 回答
7664 浏览
提问于 2025-04-16 00:49

我有以下代码:

>>> 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 有什么区别。

6 个回答

2
>>> while x < y:
...     print '{0} / {1}, '.format(x+1, y),
...     x += 1
... 
1 / 3,  2 / 3,  3 / 3, 

注意到多出来的逗号了吗?

3

我觉得使用 sys.stdout.write() 是可以的,但在 Python 2 中,标准的写法是用 print 后面加个逗号,正如 mb14 所建议的。如果你在用 Python 2.6 及以上版本,并且想要兼容 Python 3,可以使用新的 print 函数,这样写起来会更清晰:

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

你可以使用

print "something",

(后面加个逗号,这样就不会换行),所以可以试试这个

... print '{0} / {1}, '.format(x+1, y), #<= with a ,

撰写回答