Is it possible to align a print statement to the center in Python?
Asked Answered
E

2

11

I was wondering if it was possible to align a print statement in Python (newest version). For example:

print ("hello world")

would appear on the user's screen on the left side, so can i make it centre-aligned instead?

Thank you so much for your help!

= 80 (column) x 30 ( width)

Endorsement answered 8/11, 2015 at 14:19 Comment(3)
Maybe it depend on consoleTurnstile
docs.python.org/2/library/stdtypes.html#str.center if you know the console's width.Perplexed
print ("{:>30}".format("hello world"))Shellacking
F
19

First, use os.get_terminal_size() function to get the console's width(so you don't need to know your console before):

>>> import os
>>> os.get_terminal_size()
os.terminal_size(columns=80, lines=24)
>>> os.get_terminal_size().columns
80
>>> os.get_terminal_size().columns  # after I changed my console's width
97
>>> 

Then, we can use str.center():

>>> import os
>>> print("hello world".center(os.get_terminal_size().columns))
                                  hello world                                  
>>> 

So the clear code looks like:

import os

width = os.get_terminal_size().columns
print("hello world".center(width))
Foraminifer answered 8/11, 2015 at 14:26 Comment(6)
If you want to use Python to do that, the answer is No. Because Python is running inside the console.Foraminifer
@KtEwing do you mean specify a console size independently to the real console size ?Catechu
If you want to do that, then I don't know. But that would be very interesting.Foraminifer
on linux, you can call wmctrl to set the size and position of a terminal window (not a python command, but a separate program, but you could call it with subprocess or something maybe)Shipshape
@KtEwing just replace width = os.get_terminal_size().columns by width = 50 or whatever value you want for the widthCatechu
Can't figure why this does not work with "\nHello World\n"?Exeter
G
5

Knowing the console width, you can also print centered using format:

 # console width is 50 
 print "{: ^50s}".format("foo")

will print 'foo' in the middle of a 50-column console.

Glyconeogenesis answered 8/11, 2015 at 14:27 Comment(1)
In Python 3.6+ you can do this with f-strings: print(f"{: ^50s}")Cochard

© 2022 - 2024 — McMap. All rights reserved.