【问题标题】:Formatting the prompt when using the input function使用输入功能时格式化提示
【发布时间】:2011-11-20 04:03:31
【问题描述】:

我正在尝试编写一个脚本来提示用户回答附加问题。为此,我需要将一个变量传递给提示期间显示的字符串,但我很难弄清楚如何做到这一点。

我想出了以下不起作用的代码:

operand = 4
ans = input('What is 4 + {0} ?') .format(operand)

返回:

'What is 4 + {0} ?'

但我希望它是:

'What is 4 + 4 ?'

我该怎么做?

【问题讨论】:

    标签: python python-3.x string-formatting


    【解决方案1】:
    ans = input('What is 4 + {0} ?'.format(operand)) 
    

    您需要将字符串参数修改为输入。在您的代码中,您尝试格式化 input 函数返回的输入字符串

    【讨论】:

      【解决方案2】:

      format 是字符串上的一个方法,所以像这样:

      ans = input('What is 4 + {0} ?'.format(operand)) 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-02-21
        • 2015-06-07
        • 1970-01-01
        • 2017-12-01
        相关资源
        最近更新 更多