Python居中打印

0 投票
2 回答
694 浏览
提问于 2025-04-18 01:30

好的,上次我问问题的时候时机不太对,我应该问的是怎么把我提的问题居中显示在屏幕中间?上次我附上了截图,我想要的问题在屏幕的中间 :D。抱歉。

谢谢!任何帮助都非常感谢!

2 个回答

1

你可以这样定义一个特别的打印函数:

terminal_width = 80  # Change this if necessary.

def center_print(s):
    print '{:^terminal_width}'.format(s)

当你需要把内容居中输出时,就可以调用这个函数。所以在你的问题中,使用这个函数来代替print

1

这里是关于如何检测屏幕宽度的内容,具体可以参考这个链接

def center_print(s):
    import os,sys
    command = "mode con ^ | findstr Columns" if sys.platform == 'win32' else "stty size"
    ignore, columns = os.popen(command).read().split()
    print " "*((int(columns)-len(s))/2)+s

center_print("aaaaaaaaaaaaaaaa")

撰写回答