> python version 3.11.6 > os: Windows > Idle: Visual studio code (Latest version)
My code looks something like this:
from time import sleep
x = [
"H",
"E",
"L",
"L",
"O"
]
for i in x:
print(i, end="")
sleep(.5)
when I run this expected output is:
H wait E wait L wait L wait O
but output is:
A long wait then all characters instantly.
But why?
I noticed when I don’t use end argument code works well.
""Additional info"":
also tried using sys.stdout.write() same problem.
>Solution :
When you use the end="" argument in the print function, it suppresses the newline character (\n) that print normally adds at the end of each print statement.
you can use flush=True argument in the print function, to solve this:
from time import sleep
x = [
"H",
"E",
"L",
"L",
"O"
]
for i in x:
print(i, end="", flush=True)
sleep(.5)
As an alternative, you could achieve the same result by combining sys.stdout.write() and sys.stdout.flush():
import sys
from time import sleep
x = [
"H",
"E",
"L",
"L",
"O"
]
for i in x:
sys.stdout.write(i)
sys.stdout.flush() # Flush the output buffer
sleep(.5)