编程语言
首页 > 编程语言> > 如何等待和打印在同一行python

如何等待和打印在同一行python

作者:互联网

参见英文答案 > Python: multiple prints on the same line                                    14个
好吧,所以我在vpython中做这个微小的倒计时功能,我现在正在这样做

import time
print "5"
time.sleep(1)
print "4"
time.sleep(1)
print "3"
time.sleep(1)
print "2"
time.sleep(1)
print "1"
time.sleep(1)
print "0"
time.sleep(1)
print "blastoff"

当然,这实际上不是我的代码,但它很好地证明了它.
所以我想做的不是打印它
        五
        4
        3
        2
        1
        发射
我想要
     54321 Blastoff在同一条线上.
我怎么会等待一秒钟并在同一行打印charecter.请让我知道,这将是一个很大的帮助

解决方法:

试试这个:

import time

for i in range(5, 0, -1):
    print i, # print in the same line by adding a "," at the end
    time.sleep(1)
    if i == 1:
        print 'Blastoff!'

它将按预期工作:

5 4 3 2 1 Blastoff!

编辑

…或者如果你想打印所有没有空格(问题中没有明确说明):

import time
from __future__ import print_function # not necessary if using Python 3.x

for i in range(5, 0, -1):
    print(i, end="")
    time.sleep(1)
    if i == 1:
        print(' Blastoff!')

以上将打印:

54321 Blastoff!

标签:python,vpython
来源: https://codeday.me/bug/20190517/1120945.html