我创建了一个基本菜单类,如下所示:
class Menu:
def __init__(self, title, body):
self.title = title
self.body = body
def display(self):
#print the menu to the screen
我想要做的是格式化标题和正文,使它们几乎适合预制盒子。无论我作为身体传递什么,显示器都能够适合它。格式看起来像这样。
********************************************************************************
* Here's the title *
********************************************************************************
* *
* The body will go in here. Say I put a line break here ---> \n *
* it will go to the next line. I also want to keep track\n *
* \t <----- of tabs so I can space things out on lines if i have to *
* *
********************************************************************************
我认为这个标题很容易,但我迷失在身体上。
答案 0 :(得分:4)
#!/usr/bin/env python
def format_box(title, body, width=80):
box_line = lambda text: "* " + text + (" " * (width - 6 - len(text))) + " *"
print "*" * width
print box_line(title)
print "*" * width
print box_line("")
for line in body.split("\n"):
print box_line(line.expandtabs())
print box_line("")
print "*" * width
format_box(
"Here's the title",
"The body will go in here. Say I put a line break here ---> \n"
"it will go to the next line. I also want to keep track\n"
"\t<----- of tabs so I can space things out on lines if i have to"
);
答案 1 :(得分:0)
您也可以尝试使用标准'textwrap'模块