在Python的单个print()语句中使用变量打印多行

时间:2014-06-26 09:14:25

标签: python python-3.x

是否可以做这样的事情(使用python 3):

le = "\n"
var1 = 2
var2 = 5

print("INFORMATION"+le
      "-----------"+le
      "Variable1: {}".format(var1)+le
      "Variable2: {}".format(var2)+le
      )

3 个答案:

答案 0 :(得分:4)

是。看看docs

一般例子:

var1 = 2
var2 = 5
print("INFORMATION", 
      "------------",
      "Variable1: {}".format(var1),
      "Variable2: {}".format(var2), sep='\n')

答案 1 :(得分:1)

print("INFORMATION\n"
      "-----------\n"
      "Variable1: {}\n".format(var1),
      "Variable2: {}".format(var2)
      )
In [24]: print("INFORMATION"'\n'
   ....:           "-----------"'\n'
   ....:           "Variable1: {}\n".format(var1),
   ....:           "Variable2: {}".format(var2)
   ....:           )
INFORMATION
-----------
Variable1: 2
Variable2: 5


print("INFORMATION",
      "-----------",
      "Variable1: {}".format(var1),
      "Variable2: {}".format(var2),
      sep='\n')
In [30]: print("INFORMATION",
   ....:       "-----------",
   ....:       "Variable1: {}".format(var1),
   ....:       "Variable2: {}".format(var2),
   ....:       sep='\n')
INFORMATION
-----------
Variable1: 2
Variable2: 5

答案 2 :(得分:1)

您可以将此字符串存储在对象中,然后将其打印出来:

out = "INFORMATION"+le+"-----------"+le+"Variable1: {}".format(var1)+le+"Variable2: {}".format(var2)+le
print(out)

或者如果你想做得更容易,你也可以这样做:

print("INFORMATION\n-----------\nVariable1: {}\nVariable2: {}\n".format(var1, var2))

或者如果它太长而您想在代码中的不同行中省略它:

out = "Information\n" /
      "-----------\n"