Overwrite printed line in python 3.x on mac

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-24 04:23:39

问题


I'm attempting to write a program that involves the use of a coin flip, heads or tails, but so that it will print 'heads' then be replaced by 'tails' and continue doing this until it decides on an answer.

At the moment, when I run the program, it prints the 'heads' or 'tails' on the next line every time. This happens on both Idle and Terminal.

I've tried using carriage return (\r), backspace (\b) and sys.stdout.write() and .flush() but neither are working, it just keeps printing on the next line.

Is there either another way of erasing what's been printed or is there other software I can use? Here is my code:

import time
import random

offset = random.randint(0,1)

for i in range (0, 20+offset):
    if i % 2 == 0:
        print("Heads")
    else:
        print("Tails")
    print("\r")
    time.sleep(0.1)

回答1:


print writes a \n character to the end, therefore you need to modify that if you want to keep on the same line.

import time
import random

offset = random.randint(0,1)

for i in range (0, 20+offset):
    if i % 2 == 0:
        print("Heads", end='')
    else:
        print("Tails", end='')
    print("\r", end='')
    time.sleep(0.1)

Edit: That only works for python 3, If you want to use that in python 2 then you need to write to sys.stdout

import time
import random
import sys  

offset = random.randint(0,1)

for i in xrange(0, 20+offset):
    if i % 2 == 0:
        sys.stdout.write("Heads")
    else:
        sys.stdout.write("Tails")
    time.sleep(0.1)
    sys.stdout.flush()  
    sys.stdout.write("\r")  

I'm aware this might not be the fastest implemention, but It works, I could type a faster approach later



来源:https://stackoverflow.com/questions/28514938/overwrite-printed-line-in-python-3-x-on-mac

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!