【问题标题】:Want to print multiple times in single line Python [duplicate]想要在单行 Python 中多次打印 [重复]
【发布时间】:2021-07-25 20:57:35
【问题描述】:

我想制作一个程序来输出文本,就好像它是实时输入的一样。为此,我正在打印一个单词并等待 0.2 秒,然后再等待其他。

我看过这个网站:https://www.tutorialspoint.com/how-to-print-in-same-line-in-python 但问题是 print() 不断收集要打印的字符,然后在循环结束后刷新它们。所以我无法得到我想要的结果。

这是代码:

import time

time.sleep(2)

welcome = "Welcome. We will plot a graph in this program"

for i in range(len(welcome)):
    time.sleep(0.2)
    print(welcome[i], end="")

请帮助我。 谢谢。

【问题讨论】:

  • 这能回答你的问题吗? I can't simulate slow printing, always ends in error 很奇怪,我只是尝试了我用来回答这个问题的例子,但它不再起作用了。它以前肯定有效,否则我不会回答这个问题。我不确定发生了什么。
  • 关于我自己的评论;我想我在较旧的 python 安装中测试了上面的示例。 flush=True 解决了这个问题。

标签: python python-3.x


【解决方案1】:

在 python 3 中你可以使用flush=True:

for character in welcome:
    print(character, end="", flush=True)
    time.sleep(0.2)

我通过将for i in range(len(welcome)) 替换为for word in welcome 使代码更清晰,因此您只需打印character

【讨论】:

  • 更喜欢这个答案。
  • 让它更“栩栩如生”import random 然后time.sleep(random.uniform(0.05, 0.5))
【解决方案2】:

您需要刷新标准输出,因为您没有在字符串末尾使用 '\n'。

import sys
import numpy
import pandas
import matplotlib.pyplot as pl
import time


time.sleep(2)

welcome = "Welcome. We will plot a graph in this program"

for i in range(len(welcome)):
    time.sleep(0.2)
    print(welcome[i], end="")
    sys.stdout.flush()

更好的解释here.

另一个:Usage of sys.stdout.flush() method

【讨论】:

猜你喜欢
  • 2021-02-12
  • 2015-02-04
  • 2021-10-03
  • 1970-01-01
  • 1970-01-01
  • 2015-10-27
  • 1970-01-01
  • 2020-10-04
  • 1970-01-01
相关资源
最近更新 更多