How do I make the print statement from this code stay in one line?
import time
bitcoin = 0
while 1 == 1:
time.sleep(1)
print(f"Bitcoin: {bitcoin}")
How do I make the print statement from this code stay in one line?
import time
bitcoin = 0
while 1 == 1:
time.sleep(1)
print(f"Bitcoin: {bitcoin}")
Try this:
import time
bitcoin = 0
while 1 == 1:
time.sleep(1)
print(f"\r\xb[{2}KBitcoin: {bitcoin}",end='')
bitcoin+=1
basically, \r
is the escape code for carriage return, meaning it goes back to the start and writes over the previous line. \x1b[{2}K
clears the line,(the previous bitcoin value). end=''
means that print doesn't go down to a new line.
Another solution, if you know exactly what terminal coordinates you want the text is:
import time
bitcoin = 0
x=10
y=0
def posprint(string,x=0,y=0):
print('\u001b[s')
print(f'\x1b[{y};{x}H\x1b[{2}K')
print(f'\x1b[{y};{x}H',string)
print('\u001b[u',end='')
while 1 == 1:
time.sleep(1)
posprint(f"Bitcoin: {bitcoin}",x,y)
posprint
takes the coordinates you enter into it, and prints the text at those coordinates. I use ansi escape codes here to navigate to the position and clear the line before printing the string at that location.
Again, here \x1b[{2}K
clears the line, but this time \x1b[{y};{x}H
first travels to the x
and y
coordinates. Then, after clearing the line, the function goes back to the coordinates, and then finally prints the string.
The function also goes back to where the cursor was last. \u001b[s
saves the cursor position and \u001b[u
restores the position of the cursor.