Help with Python "typewriter" style printing and ANSI codes

So basically I have the really basic “typewriter” style printing function:

def typewriter(string, pause=0.05, end="\n"):
	for char in string:
		sys.stdout.write(char)
		sys.stdout.flush()
		time.sleep(pause)
	print("", end=end)

It prints out each character one at a time with a small pause in between for a cool effect. My only issue with it is that it pauses for a second when I try and write a string that contains ANSI codes. I know why it’s doing this, because it’s printing the ANSI codes you just can’t see them in the terminal.

Does anybody know of a cool trick I can use to detect when an ansi code starts and ends so I can skip the pause?

Maybe something like:

def typewriter(string, pause=0.05, end="\n"):
	for char in string:
		sys.stdout.write(char)
		sys.stdout.flush()
        if char != ANSI_CODE:
		   time.sleep(pause)
	print("", end=end)
1 Like

A bad, but quick thought is to simply call your typewriter(), then print() your ansi code, then call your typewriter() for the rest

I would suggest you use a different “Javascript-style” for loop, so you can change the position in the string you’re at:

# Instead of:
for char in string:
    # ... use char ...

# Use this instead:
i = 0
while i < len(string):
    char = string[i]
    # ... use char ...
    # now you can update i to change where in the string you are!
    i += 1

Then look for “␛[” followed by a number and a letter, and increase i accordingly.

Never mind, I figured it out on my own like a big boy

def typewriter(string, pause=0.1, end="\n"):
	skip = False
	for char in string:
		sys.stdout.write(char)
		sys.stdout.flush()
		if ord(char) < 32 or ord(char) > 126:
			skip = True
		if char == "m" and skip:
			skip = False

		if not skip:
			time.sleep(pause)
			
	print("", end=end)

although if anybody has a way to do it better I’d love to know!

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.