如何在代码中打印换行符? (Python 2.7)
示例:
print("Hello world, this is a very very long sentence with variables 1:\n%s\nVariable 2:\n%s\nVariable 3:\n%s\nVariable 4:\n%s\nVariable 5:\n%s" % (var1, var2, var3, var4, var5) )
事实上,有更多的变量,但我将这个变为5。
我确实需要' \ n'。
为了更好的可读性,我需要在代码中的几行上编写这个print
语句。但插入一些换行符会使这些换行符出现在输出上(我不想这样做)。
有没有办法不显示换行符(但保持显示所需的' \ n')?
答案 0 :(得分:2)
我个人只是使用多行字符串作为模板,使代码更清晰。如果您想要查看字符串模块,可以使用更多功能。
variables = (1, 2, 3, 4, 5)
text ="""
Hello world, this is a very ver long sentence with variables:
Varible 1:
{}
Varible 2
{}
Varible 3:
{}
Varible 4:
{}
Varible 5:
{}"""
print(text.format(*variables))
答案 1 :(得分:1)
有几种方法可以打破print语句。从你想要的描述(保持明确的换行符):
print(
"Hello world, this is a very very long sentence with variables " +
"1:\n" +
"{}\n".format(var1) +
"Variable 2:\n" +
"{}\n".format(var2) +
"Variable 3:\n" +
"{}\n".format(var3) +
...etc
)
导致:
>>> var1 = "test1"
>>> var2 = "test2"
>>> var3 = "test3"
>>> print(
"Hello world, this is a very very long sentence with variables " +
"1:\n" +
"{}\n".format(var1) +
"Variable 2:\n" +
"{}\n".format(var2) +
"Variable 3:\n" +
"{}\n".format(var3)
)
Hello world, this is a very very long sentence with variables 1:
test1
Variable 2:
test2
Variable 3:
test3
>>>
我更喜欢:
print(
"""
Hello world, this is a very very long sentence with variables 1:
{}
Variable 2:
{}
Variable 3:
{}
""".format(var1, var2, var3)
)
...得到相同的结果。
答案 2 :(得分:0)
在没有缩进标签的情况下为我工作的解决方案看起来如此:
printtxt = ("Variables {} <- {} estimation parameters are:\n"
"Retval: {}\n"
"Charge transfert:\n {} \n"
"Amount:\n {} \n"
"Stats:\n {} \n"
"ZHA:\n {} \n"
"First eig (rad):\n {} \n"
"First eig (deg.):\n {} \n"
"Trans. :\n {} \n"
"Valids:\n {} \n"
"Dot product:\n {} \n"
)
print(printtxt.format(var1, var2, var3,
var4, var5, var6,
var7, var8,
(var90,var91,var92),
var10, var11,
(np.dot(A,B.T))
)
)
这也适用于将结果写入文件:
f1.write(printtxt.format(var1, var2, var3,
var4, var5, var6,
var7, var8,
(var90,var91,var92),
var10, var11,
(np.dot(A,B.T))
)
)