6

I am creating a simple console-based Python (version 2.4) script that will be run on a Bash shell. It is a simple menu-based script that displays a set of options to the user and will do specific tasks depending on the user input.

When the script starts, I want it to clear the screen and display the menu in the center of the screen. I can get the console width from stty size. How do I go about center-aligning the text?

GPX
  • 3,506
  • 10
  • 52
  • 69

3 Answers3

9

You can use str.center

s = "hello world"
s.center(40)
>>> '              hello world               '
tread
  • 10,133
  • 17
  • 95
  • 170
  • `string.center` is deprecated and "removed in Python 3". What is the alternative? – Qwertie Sep 12 '14 at 19:52
  • 6
    @Qwertie The _function_ in the `string` module (e.g. `string.center('foo', 10)`) has been removed in Python 3. The _method_ on `str` objects is fine (e.g. `'foo'.center(10)`). – Alex Willmer Sep 22 '14 at 15:19
8

If you are using python version 3.6 (as I love to use it instead of 2.7) you can use the caret character in the format function:

>>> '{:^50}'.format('sample text')
'                   sample text                    '     # with a length of 50.

If you want to fill the gap you use:

>>> '{:*^50}'.format('sample text')
'*******************sample text********************'     # * is the fill character.
5
import shutil

def print_centre(s):
    print(s.center(shutil.get_terminal_size().columns))
Ahmer Afzal
  • 501
  • 2
  • 11
  • 24