如何将变量插入 raw_input 查询?
How do I insert a variable into a raw_input query?
我已经开始学习 Python 2.7.x "Learn Python the Hard Way" 这本书。我目前正在学习 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?
尝试:
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" 不是占位符,它会抛出相应的错误。
我已经开始学习 Python 2.7.x "Learn Python the Hard Way" 这本书。我目前正在学习 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?
尝试:
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" 不是占位符,它会抛出相应的错误。