Create a typewriter-effect animation for strings in Python
Because you tagged your question with python 3 I will provide a python 3 solution:
- Change your end character of print to an empty string:
print(..., end='')
- Add
sys.stdout.flush()
to make it print instantly (because the output is buffered)
Final code:
from time import sleep
import sys
for x in line_1:
print(x, end='')
sys.stdout.flush()
sleep(0.1)
Making it random is also very simple.
Add this import:
from random import uniform
Change your
sleep
call to the following:sleep(uniform(0, 0.3)) # random sleep from 0 to 0.3 seconds
lines = ["You have woken up in a mysterious maze",
"The building has 5 levels",
"Scans show that the floors increase in size as you go down"]
from time import sleep
import sys
for line in lines: # for each line of text (or each message)
for c in line: # for each character in each line
print(c, end='') # print a single character, and keep the cursor there.
sys.stdout.flush() # flush the buffer
sleep(0.1) # wait a little to make the effect look good.
print('') # line break (optional, could also be part of the message)
To iterate over the lines, change the loop to:
for x in (line_1, line_2, line_3):