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

Python 如何在同一行上等待和打印,python,vpython,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" 当然,这实际上不是我的代码,但它相当好地演示了它。 所以我想做的不是打印它 5. 4

好的,我在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"
当然,这实际上不是我的代码,但它相当好地演示了它。 所以我想做的不是打印它 5. 4. 3. 2. 1. 起飞 我想要 54321在同一条线上发射。 我如何等待一秒钟并在同一行上打印字符。请让我知道,这将是一个很大的帮助

试试这个:

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!
编辑

。。。或者,如果要打印所有不带空格的内容(问题中未明确说明):

以上将打印:

54321 Blastoff!

以下代码适用于Python 2和Python 3。
但是对于Python3,请参见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)
是在命令行窗口中执行此代码所必需的。在编辑shell窗口中,可以写入
stdout.write(i)
,但
'\b'
信号不会将光标向后移动,而是显示一个正方形来代替它

顺便说一下,请尝试下面的代码,看看会发生什么。
'\b'
会触发光标向后移动一个位置,替换前面的字符,因此每个字符都会在时间上写在前面一个字符的位置上。仅在命令行窗口中有效,而在“编辑外壳程序”窗口中无效

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')
复杂化(仍要在命令行窗口中执行):


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

在每个
print
语句后添加一个逗号。或者,删除条件测试并取消输入
print'Blastoff'
第2行位置(8个空格),OP希望在不使用spaces@AswinMurugesh我不是这样理解这个问题的,OP想把它们印在同一行,他明确地说了出来,仅此而已。在这个问题上,他只是没有第二次使用空格。请重新考虑否决票。
所以我想做的不是打印它,而是5 4 3 2 1发射我要54321发射
是问题所在states@AswinMurugesh“在同一行”它接着说,不要断章取义地引用。不管怎样,我编辑了我的问题来考虑这个案子。
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)