Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/352.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python中控制台上的文本居中对齐_Python_Shell_Text_Console - Fatal编程技术网

Python中控制台上的文本居中对齐

Python中控制台上的文本居中对齐,python,shell,text,console,Python,Shell,Text,Console,我正在创建一个简单的基于控制台的Python(版本2.4)脚本,该脚本将在Bash shell上运行。它是一个简单的基于菜单的脚本,向用户显示一组选项,并根据用户输入执行特定任务 当脚本启动时,我希望它清除屏幕并在屏幕中央显示菜单。我可以从stty size获取控制台宽度。如何将文本居中对齐?您可以使用 如果您使用的是python版本3.6(因为我喜欢使用它而不是2.7),则可以在格式函数中使用插入符号: >>> '{:^50}'.format('sample text') '

我正在创建一个简单的基于控制台的Python(版本2.4)脚本,该脚本将在Bash shell上运行。它是一个简单的基于菜单的脚本,向用户显示一组选项,并根据用户输入执行特定任务

当脚本启动时,我希望它清除屏幕并在屏幕中央显示菜单。我可以从
stty size
获取控制台宽度。如何将文本居中对齐?

您可以使用


如果您使用的是python版本
3.6
(因为我喜欢使用它而不是
2.7
),则可以在
格式
函数中使用
插入符号

>>> '{:^50}'.format('sample text')
'                   sample text                    '     # with a length of 50.
如果您想填补您使用的空白:

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

string.center
已被弃用并“在Python 3中删除”。另一种选择是什么?@Qwertie在Python 3中删除了
string
模块中的函数(例如
string.center('foo',10)
)。
str
对象上的方法很好(例如
'foo'.center(10)
),链接错误;事实上应该是这样
>>> '{:*^50}'.format('sample text')
'*******************sample text********************'     # * is the fill character.
import shutil

def print_centre(s):
    print(s.center(shutil.get_terminal_size().columns))