简体   繁体   中英

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. Later, if I want to stop displaying lines, I have to remove print line from everywhere.

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:

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_lines = True  # Change to False when you no longer want to print
if print_lines:
    print line

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM