How do you type words with a short amount of time between letters? (Python)

The code I wrote here (I just assume) should print letters with a small amount of time between each letter, as if someone were typing:

from sys import stdout
from time import sleep

def timedPrint(string, time):
    array = list(string)
    for x in array:
        stdout.write(x)
        sleep(time)

timedPrint("test")

But for some reason, when I call the function, it waits for the time it takes for each character to print, then it prints the entire line ("test").

Is there any way to print it as I see fit?

+4
source share
4 answers

You need to reset stdoutafter writing each character:

for x in array:
    stdout.write(x)
    stdout.flush()  # <--
    sleep(time)
+1
source

try sys.stdout.flush()in your loop.

+1
source

, , timedPrint 1 .

timedPrint("test",1)

. , ,

python something.py

, . , , IDE . , sleep() . IDE , , sleep(), , IDE. , .

0

:

import time

def slowPrint(str, t):
  for l in str:
    print l,
    time.sleep(t)

:

import time
from sys import stdout
def slowPrint(str, t):
    for l in str:
        stdout.write(l)
        stdout.flush()
        time.wait(t)

, , 4 ;)

0

All Articles