0

I want to make a program which outputs the text as if it is typed live. For that, I am printing a word and waiting for 0.2 seconds and then other.

I have saw this website: https://www.tutorialspoint.com/how-to-print-in-same-line-in-python But the thing is print() keeps on collecting the characters that are to be printed and then flush them after the loop is over. So I am not able to get the result that I want.

This is the code:

import time

time.sleep(2)

welcome = "Welcome. We will plot a graph in this program"

for i in range(len(welcome)):
    time.sleep(0.2)
    print(welcome[i], end="")

Please help me. Thanks.

2
  • Does this answer your question? I can't simulate slow printing, always ends in error It's weird, i just tried the example I used to answer this question, but it isn't working anymore. It definitely worked before, or else i wouldn't have answered that question. I'm not sure what is going on. Commented May 3, 2021 at 12:54
  • Regarding my own comment; I think i tested the above example in an older python installation. As the flush=True fixes the issue. Commented May 3, 2021 at 13:01

2 Answers 2

2

In python 3 you can use flush=True:

for character in welcome:
    print(character, end="", flush=True)
    time.sleep(0.2)

I made the code clearer by replacing for i in range(len(welcome)) by for word in welcome, so you just have to print character.

Sign up to request clarification or add additional context in comments.

2 Comments

Like this answer more.
To make it more "life-like" import random then time.sleep(random.uniform(0.05, 0.5))
0

You need to flush standard output because you don't use '\n' at the end of your string.

import sys
import numpy
import pandas
import matplotlib.pyplot as pl
import time


time.sleep(2)

welcome = "Welcome. We will plot a graph in this program"

for i in range(len(welcome)):
    time.sleep(0.2)
    print(welcome[i], end="")
    sys.stdout.flush()

Better explaination here.

Another one : Usage of sys.stdout.flush() method

2 Comments

Thanks for resolving the problem and giving the required explanation.
I got another way to flush it: stackoverflow.com/questions/230751/… It is more simple and it doesn't need sys module

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.