如何将变量插入raw_input查询?

时间:2017-04-25 06:02:38

标签: python python-2.7 variables raw-input

我已经开始使用“学习Python困难之路”一书来学习Python 2.7.x.我目前正在学习raw_input函数,我正在尝试使用不同的方法。我写了以下代码:

name = raw_input("What is your name? ")
print "Hi %s," % name,
home = raw_input("where do you live? ")

print "I hear that %s is a great place to raise a family, %s." % (home, name)

age = raw_input("How old are you, %s? ") % name

我在最后一行收到此错误:

TypeError: not all arguments converted during string formatting

如何以类似的方式使用raw_input函数并插入变量,以便自定义raw_input查询中嵌入的问题(如果我弄乱了术语,请道歉)?

理想情况下,我想按照这些方式输出一个问题:

How old are you, Bob?

1 个答案:

答案 0 :(得分:4)

尝试:

age = raw_input("How old are you, %s? " % name)

说明:

raw_input([prompt])

If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that.

所以,当你这样做时

age = raw_input("How old are you, %s? ") % name

假设您输入了Paul

所以上述陈述变为,

age = "Paul" % name

由于字符串“Paul”不是占位符,因此会抛出相应的错误。

相关问题