How to overwrite the previous print to stdout in python?

后端 未结 16 1434
别那么骄傲
别那么骄傲 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:38

    (Python3) This is what worked for me. If you just use the \010 then it will leave characters, so I tweaked it a bit to make sure it's overwriting what was there. This also allows you to have something before the first print item and only removed the length of the item.

    print("Here are some strings: ", end="")
    items = ["abcd", "abcdef", "defqrs", "lmnop", "xyz"]
    for item in items:
        print(item, end="")
        for i in range(len(item)): # only moving back the length of the item
            print("\010 \010", end="") # the trick!
            time.sleep(0.2) # so you can see what it's doing
    

提交回复
热议问题