Skip to content Skip to sidebar Skip to footer

How To Make Python Print One Character At A Time On The Same Line?

So, I've been trying to make a small program that asks a user various questions and gives branching outputs based on the input, and I've been trying to make the print text appear o

Solution 1:

A simple for loop will get you the individual characters from any string. The only real trick is to flush the output after each character to make it print immediately.

import sys, timefor c in"Hello there!":
    sys.stdout.write(c)
    sys.stdout.flush()
    time.sleep(0.1)
print

To make it a function is indeed simple:

def print1by1(text, delay=0.1):
    for c in text:
        sys.stdout.write(c)
        sys.stdout.flush()
        time.sleep(delay)
    print

print1by1("Hello there!")

Solution 2:

On python 3 you can use the sep keyword, on python 2. There's a few options.

There may be others I'm not all too familiar with python 2.

You can use sys.stdout which is a bit overkill imo.

 sys.stdout.write('H')
 sys.stdout.write('e')

Using sys again... You can clear the softspace

print"H",
 sys.stdout.softspace=0print"e",

Or,

print'H', 'e'

Or,

print"H",; print"e"

Easier, use a +

print"H" + "e"

Have a list of chars and join them, "".join is just joining the chars to a single string which is equivalent to print "He"

 my_chars = ['H', 'e']
 print"".join(my_chars)

Post a Comment for "How To Make Python Print One Character At A Time On The Same Line?"