views:

153

answers:

2

I've created a basic menu class that looks like this:

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

What I want to do is format the title and the body so they fit inside premade boxes almost. Where no matter what I pass as the body, display will be able to fit it inside. The format would look something like this.

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

The title I think will be easy but I'm getting lost on the body.

+3  A: 
#!/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"
);
John Kugelman
Thanks! Work's perfectly!
mandroid
A: 

You could also try the standard 'textwrap' module

scrible