Welcome, guest | Sign In | My Account | Store | Cart

Sometimes it is nice to print a banner line in the output of a command line script to group a section of output (say, in a log file). This little banner() function will center a given string in a line (using a character and length you can specify).

Update: Just use string.center(...) (docs) as suggested in the comments below.

Python, 33 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
def banner(text, ch='=', length=78):
    """Return a banner line centering the given text.
    
        "text" is the text to show in the banner. None can be given to have
            no text.
        "ch" (optional, default '=') is the banner line character (can
            also be a short string to repeat).
        "length" (optional, default 78) is the length of banner to make.

    Examples:
        >>> banner("Peggy Sue")
        '================================= Peggy Sue =================================='
        >>> banner("Peggy Sue", ch='-', length=50)
        '------------------- Peggy Sue --------------------'
        >>> banner("Pretty pretty pretty pretty Peggy Sue", length=40)
        'Pretty pretty pretty pretty Peggy Sue'
    """
    if text is None:
        return ch * length
    elif len(text) + 2 + len(ch)*2 > length:
        # Not enough space for even one line char (plus space) around text.
        return text
    else:
        remain = length - (len(text) + 2)
        prefix_len = remain / 2
        suffix_len = remain - prefix_len
        if len(ch) == 1:
            prefix = ch * prefix_len
            suffix = ch * suffix_len
        else:
            prefix = ch * (prefix_len/len(ch)) + ch[:prefix_len%len(ch)]
            suffix = ch * (suffix_len/len(ch)) + ch[:suffix_len%len(ch)]
        return prefix + ' ' + text + ' ' + suffix

2 comments

wanyewon 12 years, 3 months ago  # | flag

Do the same without the mess...

def banner(text, ch='=', length=78):
    spaced_text = ' %s ' % text
    banner = spaced_text.center(length, ch)
    return banner
Trent Mick 11 years, 4 months ago  # | flag

@wanyewon: Heh, learn a new thing everyday. I hadn't known about the center, rjust and ljust Python string methods. Thanks!

Created by Trent Mick on Sat, 2 Oct 2004 (PSF)
Python recipes (4591)
Trent Mick's recipes (28)

Required Modules

  • (none specified)

Other Information and Tasks