【问题标题】:How can i have a default value in cursor place for the user input in python?如何在 python 中为用户输入的光标位置设置默认值?
【发布时间】:2019-11-29 23:16:16
【问题描述】:

我想在用户输入光标中有一个默认值。

option = input("Chose an option 1. run, 0. exit to run the output: ") or 1

我已经尝试了上面的代码,但它对我不起作用。

当我运行下面的示例代码时。 示例:

option = input("Chose an option 1. run, 0. exit to run the output: ")

预期输出:

Chose an option 1. run, 0. exit to run the output: 1

用户输入光标默认为1,用户可以直接输入,也可以在回车前修改。

【问题讨论】:

标签: python python-3.x user-input default-value


【解决方案1】:

rx7 模块有这个问题的功能。

(这只适用于 windows)

import rx7
rx7.Input(prompt, default_value)
# e.g
rx7.Input("Chose an option 1. run, 0. exit to run the output: ",'1')

(我知道您的问题已经过去 11 个月了,但仍然希望它对您有所帮助)

【讨论】:

    【解决方案2】:
    def prompt(prompt, default_value):
        answer = input(prompt + ' ' + default_value + '\r' + prompt + ' ')
        if answer == "": answer = default_value
        return answer
    
    choice = prompt('Do you want to clear the contents of this folder [Y/n]?', 'Y')
    

    这里的秘密是 \r 它将使光标回到行首而不覆盖文本。然后,您使用提示覆盖文本而不打印默认值等等...如果答案是空字符串,我们将返回 default_value。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-08
      • 1970-01-01
      • 2022-10-14
      • 1970-01-01
      相关资源
      最近更新 更多