Question

I want to write code which allows me to print a word out and then it disappears and the next word prints. For example, if I have "Hello World!," the program should print "Hello" then the word disappears and then "World!" prints and then disappears. I should be able to change the speed of the printing words as well. Currently I was able to figure out how to print characters at a certain speed, but how do I print words one by one?

import time
import sys

def print_char(s):
    for c in s:
        sys.stdout.write( '%s' % c )
        sys.stdout.flush()
        time.sleep(0.1)

print_char("hello world")
Was it helpful?

Solution

Try this:

#!/usr/bin/env python3

import sys
import time

data = "this is a sentence with some words".split()

max_len=max([len(w) for w in data])
pad = " "*max_len
for w in data:
    sys.stdout.write('%s\r' % pad)
    sys.stdout.write("%s\r" % w)
    sys.stdout.flush()
    time.sleep(0.4)

print

Example, just for the fun of it

enter image description here

OTHER TIPS

If words is a list of strings:

def print_char(words):
    for s in words:
        for c in s:
            sys.stdout.write('%s' %c)
            sys.stdout.flush()
            time.sleep(0.1)
        # erase the word
        sys.stdout.write('\b'*len(s))  # backspace the cursor
        sys.stdout.write(' '*len(s))  # overwrite with spaces
        sys.stdout.write('\b'*len(s))  # backspace again, to write the next word

Based on the answer to this question:

remove last STDOUT line in Python

You can do something like this:

import time
import sys

CURSER_UP_ONE = '\x1b[1A'
ERASE_LINE = '\x1b[2K'

def delay_print(sentence, pause_between_words):
    for s in sentence.split(" "):
        sys.stdout.write( '%s' % s)
        sys.stdout.flush()
        time.sleep(pause_between_words)
        print(ERASE_LINE + CURSER_UP_ONE)

delay_print("Hello World!", 0.5)

This code will print a word at a time in my terminal, remove the last word and print the next. The last word will be deleted just before termination. Is this how you want it to work? Else let me know.

EDIT: Noticed that you also wanted to have a delay between each character print. Have updated my code accordingly.

EDIT: Based on your comment I removed char by char printing.

This might not be what youre looking for, and it might not be as fast as some of the other answers, but something that you can do is this:

import time, os

text = "This is a long sentence that has a lot of words in it.".split()

for i in range(len(text)):
    os.system("clear")
    print(text[i])
    time.sleep(0.5)
    os.system("clear")

Where text is the text you want to type, and time.sleep(XXX) is the time between words shown.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top