如何从多行打印到一行

时间:2014-09-18 01:29:44

标签: python python-3.x

我正在开发基于文本的游戏,但我对编程很新,我想做类似

的事情
from time import sleep
print('first part' sleep(1)'second part')

但这显然不起作用所以我想知道我是否可以打印线的一部分,等待,然后将第二部分打印到相同的行,但是从不同的行打印以便它可以工作

2 个答案:

答案 0 :(得分:4)

当然,这是可能的,您只需要向print()发送一些选项:

from time import sleep
print("This is the first part. ", end='', flush=True)
sleep(1)
print("This is the second part.")

end=''表示print函数不会在其打印结束时附加换行符\nflush=True表示缓冲区立即刷新,因此立即打印。尝试删除该部分,看看会发生什么。

答案 1 :(得分:0)

快速功能来做到这一点。您只需将字符串放入列表中即可。

import time

def PrintWithPauses(lists):
    for x in range(len(lists)):
        if x == len(lists):
            print(lists[x])
        else:
            print(lists[x], end='', flush=True)
            time.sleep(1)

所以如果你有这样的清单:

myList = ['hello world! ', 'StackOverflow ', 'bob ']

并跑了:

PrintWithPauses(myList)

您的输出将是:

hello world!

暂停1秒

hello world! StackOverflow

暂停1秒

hello world! StackOverflow bob