Home > Enterprise >  How to fill carriage return printed string with whitespaces until end of line?
How to fill carriage return printed string with whitespaces until end of line?

Time:07-28

I'm trying to do something that should (and perhaps is) quite simple, but I can't find a solution. I'm guessing it may be because I am not able to query the internet properly for this matter.

I am running a code that has a counter that prints an updated % of completion in a line using the carriage return character (\r) to update the same line each time.

The code iterates over a series of nations, for example Canada, USA, Argentina to name three.

When it prints the counter, it also prints the nation. Like this:

k=0
for nation in d.keys():
  k  = 1
  num_items = len(d[nation])
  ...
  <do something>
  ...
  sys.stderr.write(f"Processed {k} out of {num_items} for {nation}\r")

Now the issue comes out when Argentina is processed first, then Canada, then USA. The printed strings are:

Processed 147 out of 147 for Argentina
Processed 762 out of 762 for Canadaina
Processed 241 out of 241 for USAadaina

How do I avoid the previous line being featured in the new one while still using the carriage return?

CodePudding user response:

You can print clean line consisting of spaces and then print your new line, for example:

import random
from time import sleep

countries = ["Argentina", "USA", "Canada"]

for _ in range(10):
    # clear the line
    print(" " * 60, end="\r")

    # print new line
    print(f"Processed XXX for {random.choice(countries)}", end="\r")
    sleep(0.5)

print()
  • Related