How to overwrite the previous print to stdout in python?

后端 未结 16 1677
别那么骄傲
别那么骄傲 2020-11-22 09:46

If I had the following code:

for x in range(10):
     print x

I would get the output of

1
2
etc..

What I

16条回答
  •  生来不讨喜
    2020-11-22 10:34

    Try this:

    import time
    while True:
        print("Hi ", end="\r")
        time.sleep(1)
        print("Bob", end="\r")
        time.sleep(1)
    

    It worked for me. The end="\r" part is making it overwrite the previous line.

    WARNING!

    If you print out hi, then print out hello using \r, you’ll get hillo because the output wrote over the previous two letters. If you print out hi with spaces (which don’t show up here), then it will output hi. To fix this, print out spaces using \r.

提交回复
热议问题