python怎么撤销到上一行_python覆盖上一行

1586010002-jmsa.png

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 calculator"

acc= int(raw_input("enter accuracy:"))

if(acc>999999):

print "WARNING: this might take a VERY long time. to terminate, press CTRL+Z"

print "precision: " + str(acc)

while i < acc:

if(o==0):

hpi *= (1.0+i)/i

o = 1

elif(o==1):

hpi *= i/(1.0+i)

o = 0

else:

print "loop error."

i += 1

if i % 100000 == 0:

print str(hpi*2))

print str(hpi*2))

It basicly outputs the current pi after 100000 calculations. how can I make it overwrite the previous calculation?

解决方案

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值