在Python Shell中将文本格式化为框
我创建了一个基本的菜单类,长得像这样:
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 *
* *
********************************************************************************
我觉得标题部分应该比较简单,但我在内容部分有点迷糊。
2 个回答
1
你也可以试试标准的 'textwrap' 模块。
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"
);
当然可以!不过你没有提供具体的内容,我无法进行翻译。如果你能把需要翻译的内容发给我,我会很乐意帮你把它变得更简单易懂。