簡體   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