【问题标题】:Delete words made with print()删除用 print() 生成的单词
【发布时间】:2019-06-03 19:14:37
【问题描述】:

我想编写代码,使数字从 1 变为 2 再到 3,依此类推。

我在 Python 3 上运行它。我试过了:

import time
from sys import stdout
for i in range(1,20):
    stdout.write("\r%d" % i)
    stdout.flush()
    time.sleep(1)
stdout.write("\n") # move the cursor to the next line

但是使用该代码,我得到 12345678910111213141516171819。 有人可以帮忙吗? 编辑:我从控制台运行此代码,而不是从 IDLE 运行,它可以工作。谁能解释一下?

【问题讨论】:

  • 适用于我的测试。我的操作系统是win10,测试过python2、python3
  • 不确定为什么需要这个,如果你只想按顺序打印数字 - 1,2,1,2,1,2,1,2.... 等可能有多个一种方法可以运行循环打印这些数字并创建退出条件可能基于此序列的计数器。
  • @MarkMeyer 我认为他们的意思是“覆盖”而不是“删除”。
  • 顺便说一句,您不需要sys.stdoutprint("\r%d" % i, end='', flush=True)

标签: python-3.x


【解决方案1】:

对于我的设置,它可以工作(Arch Linux、Python3)。你是从IDE开始的吗?还是从控制台?

也许另一种方法对你有用:

import time
from sys import stdout
for i in range(1,20):
    print(i)
    time.sleep(0.1)
    stdout.write("\033[F") #back to previous line
    stdout.write("\033[K") #clear line
stdout.write("\n") # move the cursor to the next line

发现想法here。此示例在我的控制台中有效,但在我直接从 PyCharm 启动时无效。

【讨论】:

  • 我得到:1 [F[K2 [F[K3 [F[K4 [F[K5 [F[K6 [F[K7 [F[K8 [F[K9 [F[K10 [F [K11 [F[K12 [F[K13 [F[K14] [F[K15 [F[K16] [F[K17 [F[K18] [F[K19[F[K
  • 另外,我从 python shell 运行了您的代码,但我使用脚本编写了代码。 PS我正在使用IDLE
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-05-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多