How to print in the middle of the screen?
For example,
print "hello world"
in the middle of the screen instead of the beginning? Sample output will look like this:
hello world
Python 3 suggests shutil.get_terminal_size()
, and you can str.center
center using spaces:
import shutil
columns = shutil.get_terminal_size().columns
print("hello world".center(columns))
If you are not using Python 3 use os.get_terminal_size()
.
As @ br1ckb0t mentions, this is not convenient for Python 2. Instead of using a less convenient way, Id suggests switching to Python 3 instead.
Similarly, you did it manually: add extra spaces.
If you want to know something about display geometry, you have to go to the library for such things. for example curses
.
The curses module provides an interface to the curses library, the de facto standard for portable processing of additional terminals.
If this is a terminal window, do exactly what you did. If you want consistency, you can try using tab markers ( \t
) to keep things in order. Otherwise, follow Hurkyl's guidelines for using the module curses
.
>>> print "\t\t\t Hello World!"
Hello World! # Output
See @ minitech's answer for a good way to do this in Python 3, but in Python 2 it can be done with subprocess
(at least on OS X):
import subprocess
def print_centered(s):
terminal_width = int(subprocess.check_output(['stty', 'size']).split()[1])
print s.center(terminal_width)
This way you can print leading spaces:
print ' '*5, 'hello'
You can use center()
to place your text in the middle.
For example:
str = "Hello World";
print str.center(20)
I would create a helper function:
import operator
SCREEN_WIDTH = 80
centered = operator.methodcaller('center', SCREEN_WIDTH)
print(centered("hello world"))
The version of get_termial_size that should work on python2 is tested but not extensively on ubuntu:
from collections import namedtuple
def get_terminal_size():
import struct
from fcntl import ioctl
from termios import TIOCGWINSZ
Res = namedtuple("terminal_sizes", field_names=["columns","lines"])
try:
term = struct.unpack('hhhh', ioctl(0, TIOCGWINSZ, '\000' * 8))
except IOError:
return Res(24, 80)
return Res(term[0], term[1])
In [23]: print("Hello world".center(get_terminal_size().columns))
Hello world