3

I'm trying to print two strings on the same line using a timer in between. Here's the code:

import time

print "hello",
time.sleep(2)
print "world"

But it seems the program waits for two seconds then prints both strings.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Michael
  • 713
  • 10
  • 27
  • possible duplicate of [Printing without newline (print 'a',) prints a space, how to remove?](http://stackoverflow.com/questions/4499073/printing-without-newline-print-a-prints-a-space-how-to-remove) – Andy Nov 12 '14 at 14:42
  • 2
    That works fine for me, waiting between the two words. You could trying flushing `stdout` in-between (`import sys; sys.stdout.flush()`). – jonrsharpe Nov 12 '14 at 14:42

2 Answers2

10

The issue is that , by default, the console output is buffered. Since Python 3.3 print() supports the keyword argument flush (see documentation):

print('hello', flush=True)

If you use an prior versionf of python, you can force a flush like this:

import sys
sys.stdout.flush()
Gui Rava
  • 448
  • 4
  • 6
5

in python 2.7 you could use the print_function from the future package

from __future__ import print_function
from time import sleep

print("hello, ", end="")
sleep(2)
print("world!")

But like you said, this waits 2 seconds then prints both strings. In light of Gui Rava's answer you can flush stdout, here is a sample which should get you in the right direction:

import time
import sys

def _print(string):
    sys.stdout.write(string)
    sys.stdout.flush()

_print('hello ')
time.sleep(2)
_print('world')
iLoveTux
  • 3,552
  • 23
  • 31