I was trying to print the result of a loop in the same line using python 3 and after reading Python: for loop - print on the same line I managed to do it.
for x in range(1,10):
print(x, end="")
The problem now is when I insert
time.sleep(2)
before the print. I would like to print the first character, wait two seconds, then the second, wait two more seconds, etc.
Here the code:
for x in range(1,10):
time.sleep(2)
print(x, end="")
With that we wait 20 seconds (= 10*2) and only then the numbers are displayed. This is not what we expect.
What I should do to have the above expected behavior, namely wait 2 seconds, print first character, wait more 2 seconds, print second character, etc.
To print in a for loop in one line: Use a for loop to iterate over the sequence. Set the end argument of the print() function to an empty string. The items in the sequence will get printed 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.
To print without a new line in Python 3 add an extra argument to your print function telling the program that you don't want your next string to be on a new line. Here's an example: print("Hello there!", end = '') The next print function will be on the same line.
Output to stdout
is line buffered, which means the buffer is not flushed until a newline is printed.
Explicitly flush the buffer each time you print:
print(x, end="", flush=True)
Demo:
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