Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to print one character at a time but maintain print function — Python

I am developing a text-based game on Python and I wanted to have the effect where letters appear one at a time. It has to be a function because I wanted the effect to apply to almost all printed strings. I am using the code seen below, which I got from here, and it works fine for this simple example, but the problem is that it does not recognize characters like apostrophes or hyphens and it does not retain the line breaks I have already set up, so it does not work for longer amounts of text.

Is there a way to get around this? If I could have it at least recognize more characters and have it print on a new line every time I use a new slow() function, that would be great.

import sys, time    
def slow(text, delay=0.02):
    for c in text:
        sys.stdout.write(c)
        sys.stdout.flush()
        time.sleep(delay)
    print
slow("Hello!")

Thank you and apologize for the beginner question.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This can all be done with print()

It is a requirement that a newline is output after the individual characters. However, the input string may already end with ‘\n’ so don’t repeat it.

from sys import stdout
from time import sleep 

def slow(text, delay=0.1):
    if text: # only process if the string is not zero length
        for c in text:
            print(c, end='', flush=True)
            sleep(delay)
        if text[-1] != '\n':
            print()

slow("Hello world!")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading