1

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?

Ray
  • 127
  • 1
  • 1
  • 8
  • You'd want to find the width of the output screen. Check out this answer... http://stackoverflow.com/a/566752/2475084 – Al.Sal Jul 31 '14 at 02:35

2 Answers2

0

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.

cge
  • 9,552
  • 3
  • 32
  • 51
-1

This is more of a comment but i don't have enough reputation to comment :(

Firstly there is a small error in your code, the ending quote must be a double quote, or the first quote must be single

In terms of printing it in the middle; the difficulty involves getting the size of the console instance, if the user resizes the window the length will change and the text will no longer be centered. If you are interested in only working in a particular dimension (length-wise), simple get that length and divide it by two and then do something along these lines:

python3

print( ((length_console//2) - (len('Hello world')//2))*' ' + "Hello World" )

Community
  • 1
  • 1
zeroRooter
  • 100
  • 1
  • 6