-1

Basically i want to replace a printed string with another. My code reads something like: while True:, a += random.randint(1,2), time.sleep(1), print(a) This works but looks bad so i was wondering how i can replace the printed text with new text each time it prints.

  • You can find your answer here https://stackoverflow.com/questions/6169217/replace-console-output-in-python – Virgaux Pierre Jul 12 '22 at 08:45
  • Does this answer your question? [Print in one line dynamically](https://stackoverflow.com/questions/3249524/print-in-one-line-dynamically) – Berger Jul 12 '22 at 08:46
  • Along with the other answers and comments, you may also check the following post https://stackoverflow.com/questions/69139037/overwriting-a-line-after-printing-out-something – Baris Ozensel Jul 12 '22 at 13:03

3 Answers3

1

I think this link can answer your question. Try

while True:
    a += random.randint(1,2)
    time.sleep(1)
    print(a,end='\r')
sduer pang
  • 11
  • 1
0

You can use the replace() function.

Usage :

txt = "I like bananas"

x = txt.replace("bananas", "apples")

print(x)
while True: 
  a += random.randint(1,2)
  time.sleep(1)
  print(a)
  x = replace(a, "new string")
  print(x)
Shachar297
  • 599
  • 2
  • 7
0

Depends what you are trying to do:

The simple answer is use the character \r which moves back the cursor to the begin of the line:

print("Hello world\rAloha") outputs -> Aloha world

c=0
while True:
  print(c, end='\r') #remember to overwrite `end` or print will append a `\n` at the end
  c+=1

If you need anything more complicated consider using curses: https://docs.python.org/3/howto/curses.html

Probably even rich can do this kind of things but I'm not sure because I have never used it: https://pypi.org/project/rich/

Axeltherabbit
  • 680
  • 3
  • 20