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

2024-09-26 22:42:40 发布

您现在位置: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.

Tags: import版本boxyoutrue密码timehave
2条回答

如果您的控制台理解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="")

相关问题 更多 >

    热门问题