python overwrite previous line

前端 未结 2 1913
没有蜡笔的小新
没有蜡笔的小新 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:15

    Prefix your output with carriage return symbol '\r' and do not end it with line feed symbol '\n'. This will place cursor at the beginning of the current line, so output will overwrite previous its content. Pad it with some trailing blank space to guarantee overwrite. E.g.

    sys.stdout.write('\r' + str(hpi) + ' ' * 20)
    sys.stdout.flush() # important
    

    Output the final value as usual with print.

    I believe this should work both in most *nix terminal emulators and Windows console. YMMV, but this is the simplest way.

提交回复
热议问题