Python =将用户输入变成句子

问题描述 投票:0回答:4

[下面我编写了一个程序,询问您三个不同的问题,并用一个句子总结了所有这些问题。我在下面尝试的方式给了我一个错误,当我将+ choice +choice2 + choice3全部放在末尾时,用户输入的答案最后就堆积了。我应该如何在句子的特定位置分配三个用户输入?

choice = input("What is your favorite food?")
choice2 = input("What is your favorite color?")
choice3 = input("What is your favorite car?")

print("So your favorite food is " + choice "and your favorite color is " + choice2 "and your favorite car is " + choice3)

我已经在此网站Python User Input上进行了一些研究,但仍然找不到我的问题的答案。

任何帮助将不胜感激。

python
4个回答
0
投票

更改打印声明

print("So your favorite food is " + choice + "and your favorite color is " + choice2 +"and your favorite car is " + choice3)

或更干净的解决方案是使用fstrings

print(f"So your favorite food is {choice} and your favorite color is {choice2} and your favorite car is {choice3}")

0
投票

您缺少+运算符。将您的代码更改为print("So your favorite food is " + choice + " and your favorite color is " + choice2 + " and your favorite car is " + choice3)


0
投票

您在上面发布的内容几乎是正确的,但是您错过了两个+运算符(在choice和choice2之后。)>

print("So your favorite food is " + choice + "and your favorite color is " + choice2 + "and your favorite car is " + choice3)

格式化字符串的一种更好的方法是使用字符串格式化语法。

旧样式是:

print("So your favorite food is %s and your favorite color is %s and your favorite car is %s" % (choice, choice2, choice3))

更现代的用于字符串格式化的Python语法是:

print("So your favorite food is {} and your favorite color is {} and your favorite car is {}".format(choice, choice2, choice3))

有关字符串格式here的更多信息>

我更喜欢使用格式化字符串来实现更简洁的方法,如下所示:

print("So your favorite food is {} and your favorite color is {} and your favorite car is {}".format(choice, choice2, choice3))

0
投票

我更喜欢使用格式化字符串来实现更简洁的方法,如下所示:

© www.soinside.com 2019 - 2024. All rights reserved.