Home > Software engineering >  How do print a string character by character (as if someone is typing)?
How do print a string character by character (as if someone is typing)?

Time:11-28

import time
a = """Hello my name is XYZ
How are you?
"""
b= list(a)

def conti(lst):
    for alphabet in lst:
        print(alphabet, end='')
        time.sleep(0.01)
        
conti(b)

With this there is a delay of 0.01s after printing one line and not after every alphabet.

CodePudding user response:

The word you want is "letter", not "alphabet". Alphabet refers to all the letters (a-z).

Your issue is that your print is being buffered up. It IS delaying after every letter, but you don't see the text until the program ends. After all, there are only about 30 letters, so the whole thing ends in 300 milliseconds.

You need to have the output flushed after every letter:

print(alphabet, end='', flush=True)

CodePudding user response:

You can use sys.stout.write() to write a character at a time:

import sys
import time

a = """Hello my name is XYZ
How are you?
"""


def conti(s):
    for ch in s:
        sys.stdout.write(ch)
        time.sleep(0.1)


conti(a)

Since your text includes line feeds, the code is almost the same as what you had. No need to turn it into a list, you can loop over a string just as easily. I increased the delay 10x, since it goes a bit too quickly to look realistically like someone typing.

As @TimRoberts unsubtly chose to point out: depending on your terminal, the text buffer may not flush fast enough to see the effect. You can force the flush like this, so that it works in most every situation:

import sys
import time

a = """Hello my name is XYZ
How are you?
"""


def conti(s):
    for ch in s:
        sys.stdout.write(ch)
        sys.stdout.flush()
        time.sleep(0.1)


conti(a)
  • Related