繁体   English   中英

如何替换python中的打印文本行?

[英]How do i replace lines of printed text in python?

基本上我想用另一个替换打印的字符串。 我的代码如下所示: while True:, a += random.randint(1,2), time.sleep(1), print(a)这可行,但看起来很糟糕,所以我想知道如何将打印的文本替换为每次打印时都有新文本。

我认为这个链接可以回答你的问题。 尝试

while True:
    a += random.randint(1,2)
    time.sleep(1)
    print(a,end='\r')

您可以使用replace()函数。

用法 :

txt = "I like bananas"

x = txt.replace("bananas", "apples")

print(x)
while True: 
  a += random.randint(1,2)
  time.sleep(1)
  print(a)
  x = replace(a, "new string")
  print(x)

取决于您要执行的操作:

简单的答案是使用字符\r将光标移回行首:

print("Hello world\rAloha")输出 -> Aloha world

c=0
while True:
  print(c, end='\r') #remember to overwrite `end` or print will append a `\n` at the end
  c+=1

如果您需要更复杂的内容,请考虑使用curseshttps ://docs.python.org/3/howto/curses.html

可能甚至rich也可以做这种事情,但我不确定,因为我从未使用过它: https ://pypi.org/project/rich/

暂无
暂无

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

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