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

时间:2013-11-27 21:15:46

标签: python vpython

好的,所以我在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。请让我知道,这将是一个很大的帮助

3 个答案:

答案 0 :(得分:3)

试试这个:

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!

答案 1 :(得分:2)

在Python 3中,应该将end=""传递给print函数。

答案 2 :(得分:1)

以下代码适用于Python 2和Python 3 但对于Python 3,请参阅Ramchandra Apte的好答案。

from sys import stdout
from time import sleep

for i in xrange(5,0,-1):
    stdout.write(str(i))
    sleep(1)
stdout.write(' Blastoff')

为了使代码在命令行窗口中执行,str(i)是必需的。在EDIT shell窗口中,它可以写成stdout.write(i),但'\b'信号不会将光标移回,它会显示一个正方形代替它。

顺便说一下,试试下面的代码看看会发生什么。 '\b'触发光标向后移动一个位置,替换前面的字符,因此每个字符都写在它前面的字符的位置。这仅适用于命令行窗口,而不适用于EDIT shell窗口。

from sys import stdout
from time import sleep

for i in xrange(5,0,-1):
    stdout.write(str(i))
    sleep(1)
    stdout.write('\b')
stdout.write('Blastoff')


raw_input('\n\npause')

复杂化(仍然在命令行窗口中执行):

from sys import stdout
from time import sleep

tu = (' End in 24 seconds',
      ' It remains 20 seconds',
      ' Still only 16 seconds',
      ' Do you realize ? : 12 seconds left !',
      ' !!!! Hey ONLY 8 seconds !!')
for s in tu:
    stdout.write('*')
    sleep(1)
    stdout.write(s)
    sleep(2)
    stdout.write(len(s)*'\b' + len(s)*' ' + len(s)*'\b')
    sleep(1)

stdout.write(len(tu)*'\b' + len(tu)*'!' + ' ')
n = 4
for x in xrange(n,0,-1):
    stdout.write('\b!'+str(x))
    sleep(1)

stdout.write(len(tu)*'\b' + n*'\b' + '\b')
stdout.write('       # !! BLASTOUT !! #\n')
sleep(0.8)
stdout.write('      ## !! BLASTOUT !! ##\n')
sleep(0.8)
stdout.write('     ### !! BLASTOUT !! ##\n')
sleep(0.8)
stdout.write('    #### !! BLASTOUT !! ####\n')
sleep(3)