我对编码很新,我想尝试使用Python创建一个MadLib。我已经创建了输入,但我无法弄清楚如何将多个变量添加到一个打印语法中。
print("Suddenly he grabs me. tipping me across his", bodyPart1, adj1 "movement, he angles his", noun1 "so my", bodyPart2 "is resting on the", noun2 "beside him")
答案 0 :(得分:0)
您只需使用' +'运算符将字符串连接在一起,如下所示:
INPUT:
x = 'How '
y = 'are'
z = ' you?'
print('Hello ' + 'there!\n' + x + y + z + '\nGreat!')
输出:
Hello there!
How are you?
Great!
答案 1 :(得分:0)
string1 = "is"
string2 = "some"
print("This {} a {} with {} formatting.".format(string1, "string", string2)
返回
"这是一个带有一些格式的字符串。"
或者:
print("This " + string1 + " a string with " + string2 + " formatting.")
我更喜欢第一个,因为它可以让你更容易地跟踪空间等。
答案 2 :(得分:0)
你可以尝试:
print("Suddenly he grabs me. tipping me across his", bodyPart1, adj1, "movement, he angles his", noun1, "so my", bodyPart2, "is resting on the", noun2, "beside him")
或
print("Suddenly he grabs me. tipping me across his" + str(bodyPart1) + str(adj1) + "movement, he angles his" + str(noun1) + "so my" + str(bodyPart2) + "is resting on the" + str(noun2) + "beside him")
对于案例1,您需要在每个“单词”和变量后添加逗号。
第二种情况称为字符串连接。我将变量括在str()
中以确保变量类型更改为字符串,从而允许连接。
希望这有帮助。