简体   繁体   中英

How to print over the previous line in python if the previous printed value is the same as the new one?

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")

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")

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM