Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print one character at a time on one line?

Tags:

python

How would one print the string "hello world" onto one line, but one character at a time so that there is a delay between the printing of each letter? My solutions have either resulted in one character per line, or a delayed printing of the entire string at once. This is the closest I've gotten.

import time
string = 'hello world'
for char in string:
    print char
    time.sleep(.25)
like image 851
purpleladydragons Avatar asked Feb 12 '12 03:02

purpleladydragons


People also ask

How do I print multiple statements on one line?

To print multiple expressions to the same line, you can end the print statement in Python 2 with a comma ( , ). You can set the end argument to a whitespace character string to print to the same line in Python 3. With Python 3, you do have the added flexibility of changing the end argument to print on the same line.


3 Answers

Two tricks here, you need to use a stream to get everything in the right place and you also need to flush the stream buffer.

import time import sys  def delay_print(s):     for c in s:         sys.stdout.write(c)         sys.stdout.flush()         time.sleep(0.25)  delay_print("hello world") 
like image 97
Andrew Walker Avatar answered Sep 30 '22 14:09

Andrew Walker


Here's a simple trick for Python 3, since you can specify the end parameter of the print function:

>>> import time >>> string = "hello world" >>> for char in string:     print(char, end='')     time.sleep(.25)   hello world 

Have fun! The results are animated now!

like image 42
aIKid Avatar answered Sep 30 '22 15:09

aIKid


import sys
import time

string = 'hello world\n'
for char in string:
    sys.stdout.write(char)
    sys.stdout.flush()
    time.sleep(.25)
like image 40
jgritty Avatar answered Sep 30 '22 14:09

jgritty