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
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.
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.
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.
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'.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With