Print output in a single line
I have the following code:
>>> x 开发者_JS百科= 0
>>> y = 3
>>> while x < y:
... print '{0} / {1}, '.format(x+1, y)
... x += 1
Output:
1 / 3,
2 / 3,
3 / 3,
I want my output like:
1 / 3, 2 / 3, 3 / 3
I searched and found that the way to do this in a single line would be:
sys.stdout.write('{0} / {1}, '.format(x+1, y))
Is there another way of doing it? I don't exactly feel comfortable with sys.stdout.write()
since I have no idea how it is different from print
.
you can use
print "something",
(with a trailing comma, to not insert a newline), so try this
... print '{0} / {1}, '.format(x+1, y), #<= with a ,
I think that sys.stdout.write()
would be fine, but the standard way in Python 2 is print
with a trailing comma, as mb14 suggested. If you are using Python 2.6+ and want to be upward-compatible to Python 3, you can use the new print
function which offers a more readable syntax:
from __future__ import print_function
print("Hello World", end="")
No need for write
.
If you put a trailing comma after the print statement, you'll get what you need.
Caveats:
- You will need to add a blank print statement at the end if you want the next text to continue on a new line.
- May be different in Python 3.x
- There will always be at least one space added as a separator. IN this case, that is okay, because you want a space separating it anyway.
>>> while x < y:
... print '{0} / {1}, '.format(x+1, y),
... x += 1
...
1 / 3, 2 / 3, 3 / 3,
Notice the additional comma.
You can use ,
in the end of print statement.
while x<y:
print '{0} / {1}, '.format(x+1, y) ,
x += 1
You can further read this.Here is a way to achieve what you want using itertools. This will also work ok for Python3 where print becomes a function
from itertools import count, takewhile
y=3
print(", ".join("{0} / {1}".format(x,y) for x in takewhile(lambda x: x<=y,count(1))))
You may find the following approach is easier to follow
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))
The problems with using print
with a trailing comma are that you get an extra comma at the end, and no newline. It also means you have to have separate code to be forward compatible with python3
精彩评论