Is it possible to print python statements that appear in the middle of the program?
Question: I have a question regarding python statements and whether or not it is
possible to print statements such that they appear in the middle. I know that
you can just punch the space bar until the word is in the middle and then
print it, but I am sure there is a more logical way of doing it.

For example a normal print statement would be like this:

    
    
    print ("Hello World"）
    

This would result in the output:

    
    
    Hello World
    

However, how should I make it so that it comes out in the middle like this:

    
    
                                   Hello World
    

I COULD add spaces to my print statement, but I would have to eye it and it
wouldn't truly be in the middle. Is there a function or some sort that will
help me achieve this simple print problem?


Answer: Try this:

    
    
    import subprocess
    
    def printcenter(s):
        cols = int(subprocess.check_output('stty size',shell=True).split()[1])
        pos = (cols-len(s))//2
        print(pos*" "+s)
    

This will work, at least, with most Linux distributions and OS X. It depends
on "stty size" returning the rows and columns in the terminal, which may not
work depending on your situation: let us know if you're not in a standard
shell environment (eg, an iPython notebook or something similar).

If you have some other way of determining the number of columns, you can swap
out the `cols =`, and the code should still work.

Note of course that perfect centering not necessarily possible in a shell: it
depends on the ability to have an equal number of spaces on each side of the
string, which means that (cols-len(s)) must be even.

