pythonlistsyseffect

Typewriter Effect on a list


I am making the base of a game, and for the intro, I need it to print out like a typewriter. When I call it as multiple, it prints out the whole object, rather than slowly printing it out, like a typewriter would

import random
import sys
from time import sleep

test_list = ['obj 1', 'obj 2']

def writer(text, multi = True):
    if multi == True:
        obj = 0
        for item in text:
            sleep(1)
            sys.stdout.write(text[obj])
            
            obj += 1
            sys.stdout.flush()
    
    else:
        for char in text:
            sleep(0.05)
            sys.stdout.write(char)
            sys.stdout.flush()

writer(test_list)

Solution

  • "for char in item" added, "obj" removed, "sys.stdout.write('\n')" added for pretty printer.

    Code:

    import random
    import sys
    from time import sleep
    
    test_list = ['obj 1', 'obj 2']
    
    def writer(text, multi=True):
        if multi:
            for item in text:
                for char in item:
                    sleep(0.5)  # <= adjust how many secs to wait for
                    sys.stdout.write(char)
                    sys.stdout.flush()
                sys.stdout.write('\n')  
        else:
            for char in text:
                sleep(1)   # <= adjust how many secs to wait for
                sys.stdout.write(char)
                sys.stdout.flush()
            sys.stdout.write('\n')  
    
    writer(test_list)