[英]dynamic way to print same line multiple times in python
I have some set of operations and I want to display a seperation line after completing each operation. 我有一些操作,我想在完成每个操作后显示一个分隔线。 (For better readability)
(为了更好的可读性)
My code: 我的代码:
if __name__ == '__main__':
line='-'*100
print line
#do something
print line
#do something
print line
#do something
This exactly does what I want. 这正是我想要的。 But the problem here is I have 100's of operations.
但这里的问题是我有100个操作。 Later, if I want to stop displaying lines, I have to remove
print line
from everywhere. 后来,如果我想停止显示行,我必须从任何地方删除
print line
。
Another solution might be managing some global flag to check whether to display line or not. 另一个解决方案可能是管理一些全局标志以检查是否显示行。
Is there any other simple & dynamic solution to this issue ? 这个问题还有其他简单而动态的解决方案吗?
You may have fallen into the trap of copy pasting the same things 100s of time. 你可能已经陷入了复制的陷阱,在几百年的时间里粘贴了相同的东西。 I can't comment and ask, but if you're
# do somethings
are the same, you can do: 我无法发表评论并提出问题,但如果你是
# do somethings
是相同的,你可以这样做:
if __name__ == "__main__":
line = '-' * 100
for _ in range(<how many times>):
print line
# do something
If they're not the same, they should really be functions as there shouldn't be too much code outside functions. 如果它们不相同,它们应该是函数,因为函数之外不应该有太多代码。 For example,
例如,
if __name__ == '__main__':
line = '-' * 100
print line
function_a()
print line
function_b()
print line
function_c()
# etc
becomes: 变为:
if __name__ == '__main__':
line = '-' * 100
for function in (function_a, function_b, # etc
function_c):
print line
function()
Add a boolean variable at the top and use it to control the print statements: 在顶部添加一个布尔变量,并使用它来控制print语句:
print_lines = True # Change to False when you no longer want to print
if print_lines:
print line
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.