是否可以将打印语句与 Python 中的中心对齐?

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

我想知道是否可以在 Python(最新版本)中对齐打印语句。例如:

print ("hello world")

会出现在用户屏幕的左侧,所以我可以改为居中对齐吗?

非常感谢您的帮助!

= 80(列)x 30(宽度)

首先,使用 os.get_terminal_size() 函数获取控制台的宽度(因此您之前不需要知道您的控制台):

>>> 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
>>> 

然后,我们可以使用str.center():

>>> import os
>>> print("hello world".center(os.get_terminal_size().columns))
                                  hello world                                  
>>> 

所以清晰的代码如下所示:

import os

width = os.get_terminal_size().columns
print("hello world".center(width))

知道控制台宽度,您还可以使用 format:

居中打印
 # console width is 50 
 print "{: ^50s}".format("foo")

将在 50 列控制台的中间打印 'foo'。