python – How to use r to print on same line?

python – How to use r to print on same line?

Put the r at the beginning or end of your printed string, e.g. rthis string will start at the beginning of the line. or the next string will start at the beginning of the liner. Conceptually, r moves the cursor to the beginning of the line and then keeps outputting characters as normal.

You also need to tell print not to automatically put a newline character at the end of the string. In python3, you can use end= as in this previous stackoverflow answer.

Alternatively, instead of using print you can do import sys and sys.stdout.write(whatever), which sends only the exact characters to stdout without an implicit newline. Youll probably also want to use sys.stdout.flush(), without which it will store characters in a buffer rather than printing them immediately.

Add an , end=r to you print function. Also make sure your printed data has enough space to overwrite the previous printed data or be of the same length since just moving to the same line would not automatically clear the previous contents.

python – How to use r to print on same line?

You can use sys.stdout.write:

import time
import sys

def timer(t=5):
    t0 = time.time()
    now = t0
    while now-t0 < t:
        now = time.time()
        timestr = r%%%it %(100*(now-t0)/t)
        sys.stdout.write(timestr)
        sys.stdout.flush()
        time.sleep(0.1)

Leave a Reply

Your email address will not be published.