Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 712
user225312 Avatar asked Jul 05 '10 08:07

user225312


People also ask

What is the syntax to print output in a single line?

while x < y: ... print '{0} / {1}, '.

How do you print a line output?

The Python's print() function is used to print the result or output to the screen. By default, it jumps to the newline to printing the next statement. It has a pre-defined format to print the output.

How do I print all values on one line?

Modify print() method to print on the same line The print method takes an extra parameter end=” “ to keep the pointer on the same line. The end parameter can take certain values such as a space or some sign in the double quotes to separate the elements printed in the same line.

What is the syntax to print output in a single line in Python?

To print on the same line in Python, add a second argument, end=' ', to the print() function call. print("It's me.")


1 Answers

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 ,
like image 89
mb14 Avatar answered Sep 19 '22 23:09

mb14