简体   繁体   English

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

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

Basically i want to replace a printed string with another.基本上我想用另一个替换打印的字符串。 My code reads something like: while True:, a += random.randint(1,2), time.sleep(1), print(a) This works but looks bad so i was wondering how i can replace the printed text with new text each time it prints.我的代码如下所示: while True:, a += random.randint(1,2), time.sleep(1), print(a)这可行,但看起来很糟糕,所以我想知道如何将打印的文本替换为每次打印时都有新文本。

I think this link can answer your question.我认为这个链接可以回答你的问题。 Try尝试

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

You can use the replace() function.您可以使用replace()函数。

Usage :用法 :

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)

Depends what you are trying to do:取决于您要执行的操作:

The simple answer is use the character \r which moves back the cursor to the begin of the line:简单的答案是使用字符\r将光标移回行首:

print("Hello world\rAloha") outputs -> Aloha world 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

If you need anything more complicated consider using curses : https://docs.python.org/3/howto/curses.html如果您需要更复杂的内容,请考虑使用curseshttps ://docs.python.org/3/howto/curses.html

Probably even rich can do this kind of things but I'm not sure because I have never used it: https://pypi.org/project/rich/可能甚至rich也可以做这种事情,但我不确定,因为我从未使用过它: https ://pypi.org/project/rich/

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

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