问题
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