How do I get a user inputted variable into a sente

2020-05-07 18:33发布

I need to use firstnoun in the sentence "The [firstnoun] went to the lake.", where firstnoun is user inputted.

This is sort of what I have so far:

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

I need it to print:

The [firstnoun] went to the lake.

How do I do this? I tried doing

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

and variations thereof, but none of that is working. I hope the question is clear enough.

Note: I'm a few weeks into a beginner python course so we're just learning the basics. Do I have to use def main() here?

标签: python
3条回答
Summer. ? 凉城
2楼-- · 2020-05-07 18:53

Looking at the python docs, you can find multiple ways.

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))

or even using format with keywords

    print("The {noun} went to the lake".format(noun=firstnoun))
查看更多
▲ chillily
3楼-- · 2020-05-07 19:06

Use string concatenation to build the output you wish:

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

For more advanced formatting, use format():

print("The {0} went to the lake.".format(firstnoun))
查看更多
放我归山
4楼-- · 2020-05-07 19:06

You need to interpolate the value.

Here's a general example to show the concept which you can then apply to your homework:

x = "foo"

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

Also, no, a main function is not necessary.

查看更多
登录 后发表回答