Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I print in the middle of the screen?

Tags:

python

For example,

print "hello world"

in the middle of screen instead of beginning? Sample output would be like:

                                   hello world
like image 253
Euler Avatar asked Apr 21 '15 18:04

Euler


3 Answers

Python 3 offers shutil.get_terminal_size(), and you can use str.center to center using spaces:

import shutil

columns = shutil.get_terminal_size().columns
print("hello world".center(columns))

If you’re not using Python 3, use os.get_terminal_size() instead.

As @br1ckb0t mentions, this isn’t available conveniently in Python 2. Rather than using a less convenient way, though, I’d suggest switching to Python 3 instead.

like image 180
Ry- Avatar answered Oct 21 '22 00:10

Ry-


See @minitech's answer for a good way to do this on Python 3, but on Python 2, this 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)
like image 28
rickcnagy Avatar answered Oct 21 '22 01:10

rickcnagy


You could use center() to put text in the middle.

For example:

str = "Hello World";
print str.center(20)
like image 40
Tenzin Avatar answered Oct 21 '22 02:10

Tenzin