10

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)

Artjom B.
  • 61,146
  • 24
  • 125
  • 222
Kt Ewing
  • 103
  • 1
  • 1
  • 6

2 Answers2

18

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))
Remi Guan
  • 21,506
  • 17
  • 64
  • 87
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.

Karl Barker
  • 11,095
  • 3
  • 21
  • 26