簡體   English   中英

如何在raw_input查詢中插入變量?

[英]How do I insert a variable into a raw_input query?

我已經從“以艱難的方式學習Python”這本書開始學習Python2.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查詢中嵌入的問題(如果弄亂了術語,我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”不是占位符,因此會引發相應的錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM