【问题标题】:How to print over the previous line in python if the previous printed value is the same as the new one?如果前一个打印值与新值相同,如何在 python 中打印上一行?
【发布时间】:2022-12-14 10:05:56
【问题描述】:

我运行了一个无限循环,它在控制台中不断打印几乎相同的内容。为了可读性,如果它与上一个循环的内容相同,我不希望 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")

【问题讨论】:

    标签: python loops


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2017-11-23
      • 1970-01-01
      • 2018-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多