【问题标题】:how to wait and print on the same line python [duplicate]如何在同一行python等待和打印[重复]
【发布时间】:2013-12-13 17:30:50
【问题描述】:

好的,所以我在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 Blastoff 在同一条线上。 我将如何等待一秒钟并在同一行上打印字符。请告诉我,这将是一个很大的帮助

【问题讨论】:

  • 在每个print 语句后添加一个逗号。

标签: python vpython


【解决方案1】:

试试这个:

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!

【讨论】:

  • 或者,删除条件测试并取消缩进 print 'Blastoff' 第 2 行位置(8 个空格)
  • OP 想要在没有空格的情况下打印它们
  • @AswinMurugesh 这不是我理解这个问题的方式,OP 想在同一行打印它们,他明确表示,仅此而已。在这个问题中,他根本没有第二次输入空格。请重新考虑否决票。
  • so what I want to do is instead of printing it 5 4 3 2 1 Blastoff I want 54321 Blastoff 问题说明了什么
  • @AswinMurugesh “在同一行”它接下来说,不要断章取义。无论如何,我也编辑了我的问题以考虑这种情况
【解决方案2】:

以下代码适用于 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)

【讨论】:

    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-21
      • 1970-01-01
      • 2020-05-21
      • 2014-08-19
      相关资源
      最近更新 更多