Center-aligning text on console in Python

后端 未结 3 2084
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-10 08:26

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 use

相关标签:
3条回答
  • 2020-12-10 08:58

    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.
    
    0 讨论(0)
  • 2020-12-10 09:07
    import shutil
    
    def print_centre(s):
        print(s.center(shutil.get_terminal_size().columns))
    
    0 讨论(0)
  • 2020-12-10 09:13

    You can use str.center

    s = "hello world"
    s.center(40)
    >>> '              hello world               '
    
    0 讨论(0)
提交回复
热议问题