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

时间:2013-11-20 17:41:34

标签: python

我正在制作Candy Box版本。这是我到目前为止的代码

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.

2 个答案:

答案 0 :(得分:0)

如果您的控制台理解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替换为您的控制台所需的相应控制代码。

答案 1 :(得分:0)

更简单的版本(IMO)

使用'\b'返回&重写整行,从而给出 update

的感觉
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="")