Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)

like image 440
Kt Ewing Avatar asked Nov 08 '15 14:11

Kt Ewing


People also ask

How do I center a print statement in Python?

To center align a text in Python, we use the Python's string center() function. Python center() is a string class function that is used to position a string by padding it with a specified character.

How do I print something in the middle?

On the Layout tab, under Page Setup, click Margins. Click Custom Margins, and then adjust the margins as you want them to appear. To center the sheet on the page when you print, under Center on page, select Horizontally and Vertically.

Can numbers be aligned in Python?

Numbers can also be left, right, or centre aligned using python format() method. For displaying a number with left alignment, we use the “:<n” symbol inside the placeholder in the format() method.


2 Answers

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))
like image 82
Remi Crystal Avatar answered Oct 12 '22 11:10

Remi Crystal


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.

like image 36
Karl Barker Avatar answered Oct 12 '22 13:10

Karl Barker