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.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
  • Does this answer your question? [I can't simulate slow printing, always ends in error](https://stackoverflow.com/questions/64495438/i-cant-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. – Kraay89 May 03 '21 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. – Kraay89 May 03 '21 at 13:01

2 Answers2

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.

Rivers
  • 1,783
  • 1
  • 8
  • 27
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

Rallyx
  • 38
  • 8