Need Help in Python

Daniel 'Dang' Griffith noemail at noemail4u.com
Thu May 6 08:12:37 EDT 2004


""" Starter module for drawing boxes with characters.
    No warranty or suitability for use is expressed or implied.
    Daniel 'Dang' Griffith sez, "Have a nice day!".
"""

# for reference
boxchars = [chr(i) for i in xrange(129, 219)]

# handy abbreviations; roll your own naming convention
UL = upperleft = topleft                 = chr(218)
LL = lowerleft = botleft = bottomleft    = chr(192)
LR = lowerright = botright = bottomright = chr(217)
UR = upperright = topright               = chr(191)
vert = vertical                          = chr(179)
horiz = hor = horizontal                 = chr(196)

nl = newline = '\n'

# precompute the invariants
top = '%c%%s%c' % (UL, UR)
mid = '%%s%c%%s%c\n' % (vert, vert)
bot = '%c%%s%c' % (LL, LR)
all = '%s\n%%s%%s%s' % (top, bot)

def box(w, h, fill=' ', indent=''):
    """ Return a string that appears as an 'box' when printed.
        This is, of course, highly depending on the local
        character representation.
        The box is filled with spaces by default.
        The box is left-aligned by default.  To indent it, provide
        the indentation string.  This will be added to the middle 
        and bottom of the box.  The caller is responsible for 
        drawing the box at the appropriate starting position.
    """
    # exceptional cases
    if w < 1:
        raise ValueError("A box must have a width of at least 1.")
    if h < 1:
        raise ValueError("A box must have a height of at least 1.")
    # pathological cases--return value is not *really* a box
    if w == 1:
        return h * (vert + nl)
    if h == 1:
        return horiz * w
    # normal case
    end = horiz * (w - 2)
    return all % (end, (h - 2) * (mid % (indent, fill * (w - 2))),
indent, end)

#    --dang



More information about the Python-list mailing list