1

I have written this small code in Python. It should print every character in a string with a small sleeptime between them...

import time, sys

def writeText(string, t):
    i = 0
    while i < len(string):
        sys.stdout.write(string[i])
        time.sleep(float(t))
        i += 1

writeText("Hello World", 0.5)

but it only prints the whole string after 0.5 seconds... I often have this issue but I haven't found a solution yet.

2 Answers2

3

sys.stdout.flush() might solve your problem.

import time, sys

def writeText(string, t):
    i = 0
    while i < len(string):
        sys.stdout.write(string[i])
        time.sleep(float(t))
        i += 1
        sys.stdout.flush()

writeText("Hello World", 0.5)
dkato
  • 895
  • 10
  • 28
3

You should add

sys.stdout.flush()

after writing, to force the output of the text.

clemens
  • 16,716
  • 11
  • 50
  • 65