2

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 on screen on character at a time, with a short delay in between each character, but on the same line. I've seen other various methods such as

print "H",
print "e",

etc, but that is very time consuming, requiring me to type out a print for each letter. I've seen other question on this topic, and tried the code placed in them, but none seem to work so far. Would there be an easier way to print what I want, or to make this into a print style function?

EDIT: Making this a function is probably REALLY easy, but I'm a bit of a beginner with Python

L.Quinn
  • 23
  • 1
  • 4

2 Answers2

5

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, time

for 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!")
kindall
  • 178,883
  • 35
  • 278
  • 309
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=0
 print "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)
Pythonista
  • 11,377
  • 2
  • 31
  • 50