Home > OS >  How to print over the previous line in python if the previous printed value is the same as the new o
How to print over the previous line in python if the previous printed value is the same as the new o

Time:12-13

I run an infinite loop, where it keeps printing mostly the same thing in the console. For readability I do not want python to print to next line if it is the same content as the previous loop

while True:
    print("The same line again. Lets overwrite")
    if random.randint(1, 1000) == 999:
        print("It is a different line. I do not want to overwrite")

CodePudding user response:

Keep track of last thing printed, check if it is equal before you print.


import random


class NewPrinter:
    def __init__(self):
        self.lastPrint = None

    def print(self, string):
        if string != self.lastPrint:
            print(string)
            self.lastPrint = string

np = NewPrinter()

while True:
    np.print("The same line again. Lets overwrite")
    if random.randint(1, 1000) == 999:
        np.print("It is a different line. I do not want to overwrite")

CodePudding user response:

With this code you are going to set a string "new_string" to the value it should print, after that you are checking if the value is equal to the previous one, if not, then it will set the string to the new_string and print it.

string = "The same line again. Lets overwrite"
while True:
    if random.randint(1, 1000) == 999:
        new_string = "It is a different line. I do not want to overwrite"
    else:
        new_string = "The same line again. Lets overwrite"

    if string != new_string:
        string = new_string
        print(string)
  • Related