For example,
print "hello world"
in the middle of screen instead of beginning? Sample output would be like:
hello world
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.
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)
You could use center()
to put text in the middle.
For example:
str = "Hello World";
print str.center(20)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With