是否可以在Python中将print语句与中心对齐?

Kt *_*ing 2 python alignment console-output

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

print ("hello world")
Run Code Online (Sandbox Code Playgroud)

会显示在左侧的用户屏幕上,那么我可以将其设为居中对齐吗?

非常感谢你的帮助!

= 80(列)x 30(宽度)

Kev*_*uan 5

首先,使用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
>>> 
Run Code Online (Sandbox Code Playgroud)

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

>>> import os
>>> print("hello world".center(os.get_terminal_size().columns))
                                  hello world                                  
>>> 
Run Code Online (Sandbox Code Playgroud)

所以清晰的代码看起来像:

import os

width = os.get_terminal_size().columns
print("hello world".center(width))
Run Code Online (Sandbox Code Playgroud)


Kar*_*ker 5

知道控制台宽度,您还可以使用format以下方法居中打印:

 # console width is 50 
 print "{: ^50s}".format("foo")
Run Code Online (Sandbox Code Playgroud)

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