python overwrite previous line

前端 未结 2 1903
没有蜡笔的小新
没有蜡笔的小新 2021-01-04 09:35

how do you overwrite the previous print in python 2.7? I am making a simple program to calculate pi. here is the code:

o = 0
hpi = 1.0
i = 1
print \"pi calcu         


        
2条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-04 10:29

    Check out this answer. Basically \r works fine, but you have to make sure you print without the newline characters.

    cnt = 0
    print str(cnt)
    while True:
        cnt += 1
        print "\r" + str(cnt)
    

    This won't work because you print a new line every time, and \r just goes back to the previous newline.

    Adding a comma to the print statement will prevent it from printing a newline, so \b will go back to the beginning of the line you just wrote, and you can write over it.

    cnt = 0
    print str(cnt),
    while True:
        cnt += 1
        print "\r" + str(cnt),
    

提交回复
热议问题