2009-07-29 4 views
1

J'ai créé une classe de menu de base qui ressemble à ceci:texte Mise en forme dans des boîtes dans le Python Shell

class Menu: 
    def __init__(self, title, body): 
     self.title = title 
     self.body = body 
    def display(self): 
     #print the menu to the screen 

Ce que je veux faire est de formater le titre et le corps afin qu'ils intègrent l'intérieur des boîtes premade presque . Où peu importe ce que je passe comme le corps, l'affichage sera capable de l'adapter à l'intérieur. Le format ressemblerait à ceci.

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

Le titre je pense sera facile mais je me perds sur le corps.

Répondre

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

Merci! Fonctionne parfaitement! – mandroid