I want a text to be displayed as if it is just being typed. So I need a little delay after every letter.
I tried to do it this way:
import time
text
Your example prints them all on separate lines I think (at least on windows). You can use printing to sys.stdout to get around this.
import time, sys
for character in text:
sys.stdout.write(character)
time.sleep(0.2)
this line:
print char, time.sleep(0.2)
decodes as "print the value of char, and then print the return value of the function time.sleep() (which is None)".
You can break them onto separate lines, but the default behavior of print followed by a comma will leave you with spaces between the characters that you probably don't want. If not, look up how to change the behavior of print, or do something like this:
>>> import sys
>>> import time
>>> for char in "test string\n":
... sys.stdout.write(char)
... time.sleep(0.2)
...
test string
>>>
>>> import time
>>> import sys
>>> blah = "This is written slowly\n"
>>> for l in blah:
... sys.stdout.write(l)
... sys.stdout.flush()
... time.sleep(0.2)
...
This is written slowly
You're printing the return value of time.sleep(0.2) which is None. Put it on a separate line. The comma after "print char" will prevent a newline from being printed but it will introduce a single space after each character.
Try this instead:
>>> import sys
>>> import time
>>> text = "Hello, this is a test text to see if all works fine."
>>> for char in text:
... sys.stdout.write(char)
... time.sleep(0.2)
Put the time.sleep in a separate line. With a comma, you are printing its return value as well.
Thank you all for your help, this is my final code, I made a random timing for the delay as mentioned by Wooble:
import time
import sys
from random import randrange
text = "This is the introduction text."
for c in text:
sys.stdout.write(c)
sys.stdout.flush()
seconds = "0." + str(randrange(1, 4, 1))
seconds = float(seconds)
time.sleep(seconds)