Welcome, guest | Sign In | My Account | Store | Cart

Snippet to output lines of characters with effect in python

Python, 13 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
#!/usr/bin/python3

import sys
import time

string = input('Any string you want: ')
s = 0
while s < len(string):
    sys.stdout.write(string[s])
    sys.stdout.flush()
    time.sleep(0.06) # set the time milliseconds for faster output
    s = s + 1
sys.stdout.write('\n')

2 comments

Enrico Giampieri 9 years, 1 month ago  # | flag

It could be written in a slightly more pythonic way:

import sys
import time
string = """Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Etiam est mauris, egestas sit amet fermentum et, viverra vitae odio.
In nec molestie mi."""

for s in string:
    sys.stdout.write(s)
    sys.stdout.flush()
    time.sleep(0.06) # set the time milliseconds for faster output
    sys.stdout.flush()
sys.stdout.write('\n')

If you want something more in line with the interactive novel style, you can also split your line around the full stops:

dt = 0.06
for phrase in string.split('.'):
    p = phrase.strip()       #remove the spaces and newlines at the beginning
    if not p:                #if it's and empty string, do not print it
        continue
    for s in p:              #for every char in the phrase
        sys.stdout.write(s)
        sys.stdout.flush()
        time.sleep(dt)       # set the time milliseconds for faster output
    sys.stdout.write('.\n')
    sys.stdout.flush()
    time.sleep(dt*10)        #wait for a longer time after a full stop
p@ntut$ (author) 9 years, 1 month ago  # | flag

Cool man! Thanks for that!

Created by p@ntut$ on Wed, 17 Oct 2012 (GPL3)
Python recipes (4591)
p@ntut$'s recipes (7)

Required Modules

  • (none specified)

Other Information and Tasks