繁体   English   中英

如果前一个打印值与新值相同,如何在 python 中打印上一行?

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

我运行了一个无限循环,它在控制台中不断打印几乎相同的内容。 为了可读性,如果它与上一个循环的内容相同,我不希望 python 打印到下一行

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

跟踪最后打印的东西,在打印前检查它是否相等。


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

使用此代码,您将设置一个字符串“new_string”为其应打印的值,之后您将检查该值是否等于前一个值,如果不相等,则它将字符串设置为 new_string 并打印它.

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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