簡體   English   中英

用另一行替換一行文本(Python)

[英]Replacing one line of text with another (Python)

我正在制作糖果盒的版本。 到目前為止,這是我的代碼

import time 
print("Candy box")
candy = 0
while True:
    time.sleep(1)
    candy += 1
    print("You have ", candy, " candies.")

問題是當我要更新最后一行時,這將輸出很多行。 例:

代替:

You have 3 candies.
You have 4 candies.
You have 5 candies.

這將是:

You have 3 candies.

然后它將變成:

You have 4 candies.

如果您的控制台了解ANSI控制代碼,則可以使用以下命令:

#! /usr/bin/python3

import time

print ('Candy box\n')
candies = 0
while True:
    time.sleep (1)
    print ('\x1b[FYou have {} cand{}.\x1b[J'.format (candies, 'y' if candies == 1 else 'ies') )
    candies += 1

如果您的控制台不理解ANSI,請用您的控制台期望的相應控制代碼替換CSI FCSI J

較簡單的版本(IMO)

使用'\\b'返回並重新編寫了整行,從而產生了更新

import time
print("Candy box\n")
candies = 0
backspace = 0 # character count for going to .
while True:
    time.sleep(1)
    candies += 1
    if candies == 1:
        to_print = 'You have 1 candy.'
    else:
        to_print = 'You have %s candies.'%candies

    backspace = len(to_print)  # update number of characters to delete
    print(to_print+'\b'*backspace, end="")

您也可以嘗試以下

import time
print("Candy box\n")
candies = 0

to_print = 'You have 1 candy.'
backspace = len(to_print)      # character count for going to .
print(to_print+'\b'*backspace, end="")

while True:
    time.sleep(1)
    candies += 1
    to_print = 'You have %s candies.'%candies
    backspace = len(to_print)  # update number of characters to delete
    print(to_print+'\b'*backspace, end="")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM