2009-07-29 33 views
1

我已經創建了一個基本的菜單類,看起來像這樣:設置文本格式成箱在Python殼牌

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   * 
*                    * 
******************************************************************************** 

標題我覺得很容易,但我迷失在身體上。

回答

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" 
); 
+0

謝謝!工作完美! – mandroid 2009-07-29 21:29:25