Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print new output on same line [duplicate]

I want to print the looped output to the screen on the same line.

How do I this in the simplest way for Python 3.x

I know this question has been asked for Python 2.7 by using a comma at the end of the line i.e. print I, but I can't find a solution for Python 3.x.

i = 0  while i <10:      i += 1       ## print (i) # python 2.7 would be print i,      print (i) # python 2.7 would be 'print i,' 

Screen output.

1 2 3 4 5 6 7 8 9 10 

What I want to print is:

12345678910 

New readers visit this link aswell http://docs.python.org/release/3.0.1/whatsnew/3.0.html

like image 647
onxx Avatar asked Aug 20 '12 04:08

onxx


People also ask

How do I print multiple things on the same line?

To print multiple expressions to the same line, you can end the print statement in Python 2 with a comma ( , ). You can set the end argument to a whitespace character string to print to the same line in Python 3. With Python 3, you do have the added flexibility of changing the end argument to print on the same line.

How do I display output on the same 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.

How do you print overwrite on the same line in Python?

Summary: The most straightforward way to overwrite the previous print to stdout is to set the carriage return ( '\r' ) character within the print statement as print(string, end = "\r") . This returns the next stdout line to the beginning of the line without proceeding to the next line.

How do you print a string multiple times on a new line?

The multiplication operator (*) prints a string multiple times in the same line. Multiplying a string with an integer n concatenates the string with itself n times. To print the strings multiple times in a new line, we can append the string with the newline character '\n'.


1 Answers

From help(print):

Help on built-in function print in module builtins:  print(...)     print(value, ..., sep=' ', end='\n', file=sys.stdout)      Prints the values to a stream, or to sys.stdout by default.     Optional keyword arguments:     file: a file-like object (stream); defaults to the current sys.stdout.     sep:  string inserted between values, default a space.     end:  string appended after the last value, default a newline. 

You can use the end keyword:

>>> for i in range(1, 11): ...     print(i, end='') ...  12345678910>>>  

Note that you'll have to print() the final newline yourself. BTW, you won't get "12345678910" in Python 2 with the trailing comma, you'll get 1 2 3 4 5 6 7 8 9 10 instead.

like image 59
DSM Avatar answered Sep 22 '22 10:09

DSM