简体   繁体   中英

Replacing one line of text with another (Python)

I'm making a version of Candy Box. Here is my code so far

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

The problem is that this will output many lines one after the other when I want the last to be updated. Example:

Instead of:

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

It would be:

You have 3 candies.

And then it would turn into:

You have 4 candies.

If your console understands ANSI control codes, you can use this:

#! /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

If your console doesn't understand ANSI, replace CSI F and CSI J with the corresponding control codes your console expects.

A simpler version (IMO)

Used the '\\b' to go back & re-write the whole line, thus giving a sense of 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="")

You could also try the following

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="")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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