如何在Python中当新内容与上一行相同时覆盖上一行打印?
实现相同内容覆盖打印、不同内容换行的无限循环
要实现相同内容不换行覆盖、不同内容换行打印的效果,核心是利用**回车符\r**让光标回到当前行开头,覆盖原有内容,同时记录上一次的输出内容做判断。
修改后的代码示例
import random # 初始化上一次输出的内容 last_output = "" while True: # 生成当前要输出的内容 current_output = "The same line again. Lets overwrite" if random.randint(1, 1000) == 999: current_output = "It is a different line. I do not want to overwrite" if current_output == last_output: # 内容相同,用\r回到行首覆盖打印,end=''避免自动换行 print(f"\r{current_output}", end='', flush=True) else: # 内容不同,换行打印并更新记录的上一次内容 print(current_output) last_output = current_output
关键说明
\r:回车符,会将光标移动到当前行开头,后续输出会直接覆盖该行原有内容。flush=True:强制刷新输出缓冲区,确保内容立即显示在控制台(部分环境下默认缓冲可能导致内容不及时更新)。last_output:用于记录上一次的输出内容,作为判断当前内容是否需要覆盖或换行的依据。
内容的提问来源于stack exchange,提问作者Rajesh Kanna
相关产品推荐
相关产品推荐

