使用input函数时如何格式化提示信息
我正在尝试写一个脚本,让用户回答一个加法题。为此,我需要在提示时把一个变量放到显示的字符串里,但我一直搞不清楚该怎么做。
我写了以下代码,但它不管用:
operand = 4
ans = input('What is 4 + {0} ?') .format(operand)
返回的是:
'What is 4 + {0} ?'
但我希望它能显示成:
'What is 4 + 4 ?'
我该怎么做呢?
2 个回答
2
format是字符串上的一种方法,所以可以这样使用:
ans = input('What is 4 + {0} ?'.format(operand))
4
ans = input('What is 4 + {0} ?'.format(operand))
你需要修改传给输入的字符串参数。在你的代码中,你试图对 input
函数返回的输入字符串进行格式化。