0

I have a loop in python that is sleeping 0.1 seconds every iteration. It is sequentially printing out a string to the console. I want it to add a character every iteration, But the problem is that it waits until the loop is finished to display the text. This only happens when I have the ", end='' " bit at the end of the print call.

import time

def speak(text):
    i = 0
    for i in range(0, len(text) + 1):
        print(text[i], end='')
        i += 1
        time.sleep(0.1)

speak("Test 123. Can you see me?")
user94559
  • 59,196
  • 6
  • 103
  • 103

1 Answers1

0

As the comments say, you need flush=True in your call to print(...).

Also, your loop goes one character off the end of the string (causing an exception), and it would be nice to print a newline at the end of the text. Here's a fixed up version that works on my machine:

import time

def speak(text):
    for c in text + '\n':
        print(c, end='', flush=True)
        time.sleep(0.1)

speak("Test 123. Can you see me?")
user94559
  • 59,196
  • 6
  • 103
  • 103