You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取Python中input()函数的提示文本?

问题解答

是否可以实现?

可以实现,但默认的input()函数无法直接做到——它仅返回用户输入的字符串,而非包含提示文本的对象。

具体实现方法

需要自定义一个包装函数,在调用原生input()的同时保存提示文本,再将用户输入内容与提示文本一起返回。以下是两种常用方案:

方案1:使用自定义类(面向对象风格)

class InputResult:
    def __init__(self, value, prompt):
        self.value = value
        self.prompt = prompt

def custom_input(prompt=""):
    user_input = input(prompt)
    return InputResult(user_input, prompt)

# 使用示例
ipt = custom_input("This is some input text")
print(ipt.value)       # 输出用户输入的内容
print(ipt.prompt)      # 输出提示文本:"This is some input text"

方案2:使用字典(轻量风格)

def custom_input(prompt=""):
    user_input = input(prompt)
    return {"value": user_input, "prompt": prompt}

# 使用示例
ipt = custom_input("This is some input text")
print(ipt["value"])    # 输出用户输入的内容
print(ipt["prompt"])   # 输出提示文本:"This is some input text"

适配动态提示文本的说明

无论提示文本是静态固定还是动态生成(比如通过变量、函数返回值拼接),上述方案都能正常保存并返回提示文本——因为custom_input()会直接接收传入的动态提示文本,同步存储后返回。

内容的提问来源于stack exchange,提问作者benz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 18:10:48