1

I am trying to print 1 letter at a time on the same line, but it prints it all at once instead

this is the code I tried:

import time
text = ["f", "i", "n", "e"]
x = 0

while x <= 3:
    print(text[0], end="")
    text.remove(text[0])
    x += 1
    time.sleep(0.1)
Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70

2 Answers2

3

Standard output is line-buffered by default: nothing is actually written to standard output until a full line has been printed. You need to flush each character explicitly, most simply with the flush keyword argument.

for c in text:
    print(c, end="", flush=True)
chepner
  • 497,756
  • 71
  • 530
  • 681
0

The problem is that print() buffers. This means that it stores characters in memory rather than sending each character to output. This makes printing much more efficient because sending data to output takes a lot of time.

You can force print() to output immediately by setting flush=True:

print(text[0], end="", flush=True)

You should also iterate over the text directly:

import time
text = "fine"

for c in text
    print(c, end="", flush=True)
    time.sleep(0.1)
Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268