2014-09-24 61 views
0

我需要在第一个名词是用户输入的句子中使用第一个名词“[firstnoun]去湖边”。如何获取用户输入的变量?

这有点什么我到目前为止有:

firstnoun = input("Enter your first noun here: ") 

我需要它打印:

的[firstnoun]跑到湖边。

我该怎么做?我试过

print("The" (print(firstnoun)) "went to the lake.") 

及其变化,但没有任何工作。我希望这个问题很清楚。

注意:我进入初学Python课程的几个星期,所以我们只是在学习基础知识。我必须在这里使用def main()吗?

+0

您已经了解了字符串连接了吗? 'print(''+ firstnoun +'去了湖')'应该这样做。注意“+”。此外,在您的问题中,请将您的代码行格式化为代码块,以便于阅读...您可以突出显示该行,然后单击“{}”按钮。 – Ajean 2014-09-24 00:58:21

回答

1

使用字符串连接来构建你想输出:

print("The " + firstnoun + " went to the lake.") 

对于更高级的格式,使用format()

print("The {0} went to the lake.".format(firstnoun)) 
0

您需要插值值。

这里有一个一般的例子来说明这个概念,然后您可以应用到你的家庭作业:

X = “foo” 的

print("The word is {0}".format(x))

此外,没有,一个main功能是没有必要的。

3

看着the python docs,你可以找到多种方式。

firstnoun = input("Enter your first noun here:") 

print("The " + firstnoun + " went to the lake") 
print("The %s went to the lake" % firstnoun) 
print("The {} went to the lake".format(firstnoun)) 

甚至使用format关键字

print("The {noun} went to the lake".format(noun=firstnoun)) 
+0

很高兴展示3种方式。字符串连接可能会更慢,至少如果你做了很多。 – user1277476 2014-09-24 01:02:48

+0

是的,字符串连接是我最不喜欢的方式,因为你很容易遇到像试图连接非字符串像数字一样的问题,而字符串格式与这些值一起工作也很好。 – Hamatti 2014-09-24 01:04:46

相关问题