-2

I'm trying to delete the last character I've printed from the previous line in python, e.g if I do print ("hello world") I will get hello world outputted, but I'm wondering after it's been outputted would there be a way to remove the d at the end of the output so it would now only say hello worl... in short is there a way to remove the end character of an already printed line?

Thanks

  • 4
    Related reading: [Replace console output in Python](https://stackoverflow.com/q/6169217/953482), [Output to the same line overwriting previous](https://stackoverflow.com/q/26584003/953482) – Kevin Oct 18 '18 at 14:25
  • `print("\b ",end="")` (move the cursor back then print a space) should work *sometimes*, but don't count on it. – SIGSTACKFAULT Oct 18 '18 at 14:27

1 Answers1

0

There is no way to perform operations on data that has been output since it is not stored in memory as a variable. You can however overwrite the location on the screen (if you are dealing with something like a terminal) that it is printed on to 'remove' the old data.

Here is a function you can add and call in your code to send text to a specific location on the terminal display:

import sys

def PrintLocate(row, column, text):
    sys.stdout.write("\x1b7\x1b[%d;%df%s\x1b8" % (row, column, text))
    sys.stdout.flush()

# Elsewhere
PrintLocate(13, 37, "Hello World")
PrintLocate(13, 37 + len("Hello Worl"), " ")
Ctrl S
  • 1,053
  • 12
  • 31
  • 2
    The first part is obvious; it's the second part that OP wants. So, how to do it? – tobias_k Oct 18 '18 at 14:36
  • How do you know that? – Ctrl S Oct 18 '18 at 14:38
  • Well... I don't _know_, but isn't it _pretty_ obvious that OP does not want to overwrite a character that was "printed" to paper, but instead wants to overwrite what was last printed with the `print` function to the terminal? – tobias_k Oct 18 '18 at 14:41
  • Maybe not paper, but possibly the Output tab in Visual Studio for example... I just used paper to explain a concept. – Ctrl S Oct 18 '18 at 14:43