【问题标题】:python 3 How to print on a previous input linepython 3如何在前一个输入行上打印
【发布时间】:2017-03-21 10:21:45
【问题描述】:

我知道您可以使用 end="" 例如在上一行打印

import time

print("Loading",end="")
for i in range(3):
    print(".",end="")

但是有没有办法通过输入来做到这一点,因为它会出现错误。 例如,用户被问到一个问题,然后他们输入一个答案,它会在输入旁边打印一个 ✘ 或 ✔。

#Doesn't work
print("What is the capital of england?")
ans = input("+-> ",end="")

if ans == "London":
    print("✔")
else:
    print("✘")

这不是使用 end="" 而是使用不同的方式?

PS \r 和 \b 不起作用

【问题讨论】:

  • 如果你想要类似的东西,你应该使用 ncurses

标签: python python-3.x printing


【解决方案1】:

这是使用ANSI/VT100 Terminal Control Escape Sequences的一种方式

In [103]: def ask():
              CURSOR_UP_ONE = '\x1b[1A'
              ERASE_LINE = '\x1b[2K'
              message = "What is the capital of england? "
              answer = input(message)
              if answer == "London":
                  print(CURSOR_UP_ONE + ERASE_LINE + message + answer + "✔")
              else:
                  print(CURSOR_UP_ONE + ERASE_LINE + message + answer + "✘")
   .....: 

In [104]: ask()
What is the capital of england? Paris✘

【讨论】:

    【解决方案2】:

    除非您在输入后使用新行,否则 Python 不会读取 STDIN 来获取输入。

    所以,您不能在输入后立即打印消息。

    【讨论】:

      【解决方案3】:

      您的问题有点不清楚。但据我所知,以下是答案。

      print("what is capital of England")
      inp = input()
      
      if(inp =="London"):
          print(inp+"->✔")
      else:
          print(inp+"->✘")
      

      【讨论】:

      • 谢谢,但我希望将 ✘ 或 ✔ 打印在与输入相同的行上,而不是将用户的答案与 ✘ 或 ✔ 一起打印在下一行。
      猜你喜欢
      • 1970-01-01
      • 2022-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多