-2

I want to make a game in the python console, so I need to write out lines, and then re-write them. I started building up code for it, and came up with this:

import sys


while 1:
  #I will calculate what to write here, and store it in display
  display = ["thing", "other thing", "2nd other thing"]

  #Move the writing start back to the beginning
  for x in display: sys.stdout.write("\r")
  #Write the contents of display
  for x in display: sys.stdout.write(x + "\n")

However, the code does not erase the previously written text. It just repetitively prints the display list. How can I make it erase the text?

martineau
  • 119,623
  • 25
  • 170
  • 301

2 Answers2

0

Edit:

Similar Answer How to overwrite the previous print to stdout in python?

Method:

You can do this by printing out as many whitespaces as you have characters on that line However this would only be possible in a clean manner if you know the length of everything being printed. For example if you know the length you can do the following

print("\r")
print(" " * length_of_line)
print("\r")

Otherwise if printing long line isn't a concern, you can adopt the brute-force method of print a load of whitespaces and hope it overwrites the whole line

print("\r")
print(" " * a_large_number)
print("\r")
RossM
  • 438
  • 4
  • 10
0

You cannot use the "\r" separately from the print statement and I think you can only use it in this way with the print statement.

An implementation with the print statement would look like this:

for i in range(3): #No endless loop
    display = ["thing", "other thing", "2nd other thing"]
    for x in display: print(x, end="\r")

This would result in every line overwriting the previous one. Also have a look here, there they also discuss different methods.

Rubinjo
  • 3
  • 2
  • If you know that this question is asked here already and is a duplicate, please don't answer it. Instead, flag it as a duplicate – Tomerikoo Dec 30 '21 at 00:23