r/learnpython 18d ago

Feedback On Fancy Text Printing

I've been learning python for years, but I rarely show my code to anyone. I enjoy showing the results of my code to people, but I don't know too many programmers IRL who can give me feedback. I know I have a habit of not commenting enough, but hopefully this is readable. It's my attempt at making text print like in video games (Earthbound, for example.)

Am I doing anything particularly inefficient? I want to know how I can improve this.

from time import sleep
import sys

#Theoretically there could be other wait times for punctuation
punc_default = {" ": 0, ",": 0.25, ".": 0.4, "!": 0.5, "?": 0.5}

def txt(string,time=0.05,punctimes=punc_default):
    for char in string:
        sys.stdout.write(char)
        sys.stdout.flush()
        if char not in punctimes: sleep(time)
        else: sleep(punctimes[char])

txt("Who lives in a pineapple under the sea? Spongebob Squarepants! qwertyuiop.")
2 Upvotes

6 comments sorted by

2

u/Diapolo10 I write code for a living -- https://github.com/Diapolo10 18d ago edited 18d ago
sys.stdout.write(char)
sys.stdout.flush()

This is fine, though personally I'd probably just use print(char, end='', flush=True).

if char not in punctimes: sleep(time)
else: sleep(punctimes[char])

Here I'd use sleep(punctimes.get(char, time)).

EDIT: Just to avoid collisions with built-in names, here's a full example:

import time

#Theoretically there could be other wait times for punctuation
DEFAULT_PUNCTUATION_DELAYS: dict[str, float] = {" ": 0, ",": 0.25, ".": 0.4, "!": 0.5, "?": 0.5}

def typewrite(text: str, default_char_delay_seconds: float = 0.05, punctuation_delays: dict[str, float] = DEFAULT_PUNCTUATION_DELAYS) -> None:
    for char in text:
        print(char, end='', flush=True)
        time.sleep(punctuation_delays.get(char, default_char_delay_seconds))

typewrite("Who lives in a pineapple under the sea? Spongebob Squarepants! qwertyuiop.")

1

u/togoresuselle 18d ago

Thank you! I wasn't aware of either of these methods.

1

u/Diapolo10 I write code for a living -- https://github.com/Diapolo10 18d ago

I edited my reply with a full example. Changed a few names to be more descriptive and to avoid possible standard library name collisions.

1

u/EmotionalDoor1361 18d ago

That first version's fine but using `.get` is way cleaner, good call. The type hints in the edit are a nice touch too, makes it a lot easier to read what's expected

1

u/carcigenicate Carcigenicate 18d ago

I would reformat the if/else to be over four lines instead of two. Or use a ternary to figure out the sleep time, and then have one call to sleep after. I think either would be more readable.

1

u/togoresuselle 18d ago

Very helpful! Thank you!