【发布时间】:2020-10-14 08:46:45
【问题描述】:
我想在打印终端/控制台之前将多行字符串(包含换行符 (\n))居中。
columns = shutil.get_terminal_size().columns 给了我输出控制台的宽度,print(""" test string """.center(columns)) 将字符串打印到中心。
下面的代码打印一个带有点坐标的盒子的表示:
import shutil
X1,Y1,X2,Y2 = 90, 120, 162, 161
def print_box():
def foo(a,b):
if a<b: return ((b-a)//2)+a
else : return ((a-b)//2)+b
center_line = foo(X1,X2),foo(Y1,Y2)
tc = foo(X1,center_line[0]),foo(Y1,center_line[1])
bc = foo(X2,center_line[0]),foo(Y2,center_line[1])
string = f"""
Main box
{(X1,Y1)}
(x1,y1) ------------
| |
| Top box |
| { tc } |
| |
|------------------| {center_line}
| |
| Bottom box |
| { bc } |
| |
-------------(x2,y2)
{(X2,Y2)}
"""
columns = shutil.get_terminal_size().columns
print(f"""columns {columns}""".center(columns)) # MULTI LINE STRING WITH NO NEW LINES
print(f"""columns\n {columns}""".center(columns)) # MULTI LINE STRING WITH NEW LINES
print(string.center(columns)) # MULTI LINE STRING WITH NEW LINES
print_box()
运行它输出:
columns 104
columns
104
Main box
(90, 120)
(x1,y1) ------------
| |
| Top box |
| (108, 130) |
| |
|------------------| (126, 140)
| |
| Bottom box |
| (144, 150) |
| |
-------------(x2,y2)
(162, 161)
我希望它输出:
columns 104
columns
104
Main box
(90, 120)
(x1,y1) ------------
| |
| Top box |
| (108, 130) |
| |
|------------------| (126, 140)
| |
| Bottom box |
| (144, 150) |
| |
-------------(x2,y2)
(162, 161)
【问题讨论】:
-
您是否尝试将更多列作为参数传递给
string.center? -
这不可能是产生此输出的代码,正如代码中所说的
print("coums"),但输出显示的是columns。请仔细检查并创建一个minimal reproducible example。 -
抱歉错字我会改正的
标签: python string terminal console center