如何使用python在文本中添加多个变量

2024-05-16 23:42:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我对编码非常陌生,我想尝试使用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")


Tags: 编码语法meheacrossprintmadlibhis
3条回答

只需使用“+”运算符将字符串串联在一起,如下所示:

输入:

x = 'How '
y = 'are'
z = ' you?'

print('Hello ' + 'there!\n' + x + y + z + '\nGreat!') 

输出:

Hello there!
How are you?
Great!

你可以试试:

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()中,以确保变量类型更改为string,从而允许串联。你知道吗

希望这有帮助。你知道吗

string1 = "is" string2 = "some" print("This {} a {} with {} formatting.".format(string1, "string", string2)

退货

“这是一个带有某些格式的字符串。”

或者:

print("This " + string1 + " a string with " + string2 + " formatting.")

我更喜欢第一个,因为它可以让你更容易地跟踪空间等。你知道吗

相关问题 更多 >