【问题标题】:How to add multiple variables in text using python如何使用python在文本中添加多个变量
【发布时间】:2018-03-01 20:57:10
【问题描述】:

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

【问题讨论】:

  • 我认为你只是少了几个逗号
  • 你有碎片;唯一的问题是语言语法的细节。你被困在哪里了?

标签: python


【解决方案1】:

您只需要简单地使用“+”运算符将字符串连接在一起,如下所示:

输入:

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

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

输出:

Hello there!
How are you?
Great!

【讨论】:

    【解决方案2】:

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

    返回

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

    交替:

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

    我更喜欢第一个,因为它可以让您更轻松地跟踪空间等。

    【讨论】:

      【解决方案3】:

      你可以试试:

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

      对于第一种情况,您需要在每个“单词”和变量后添加逗号。 第二种情况称为字符串连接。我将变量包含在str() 中,以确保变量类型更改为字符串,从而允许连接。

      希望这会有所帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-06-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-20
        • 1970-01-01
        • 2018-11-12
        • 2014-05-30
        相关资源
        最近更新 更多