user225312
user225312

Reputation: 131567

Print output in a single line

I have the following code:

>>> x = 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.

Upvotes: 6

Views: 7844

Answers (6)

John La Rooy
John La Rooy

Reputation: 304117

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

Upvotes: -1

bhups
bhups

Reputation: 14875

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.

Upvotes: 2

Philipp
Philipp

Reputation: 49792

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="")

Upvotes: 3

Mad Scientist
Mad Scientist

Reputation: 18553

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

Notice the additional comma.

Upvotes: 2

Oddthinking
Oddthinking

Reputation: 25272

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.

Upvotes: 2

mb14
mb14

Reputation: 22596

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 ,

Upvotes: 6

Related Questions