|
def banner(text, width=40): |
|
"""Print the received text in a banner-style box""" |
|
|
|
STARS = "".center(width, "*") |
|
BLANK = "{}{}{}".format("*", "".center(width - 2), "*", ) |
|
usable_text_length = width - 4 |
|
|
|
print() |
|
print(STARS) |
|
print(BLANK) |
|
|
|
# Remove extra spaces but NOT newlines, and split on remaining spaces. |
|
# This is to let the caller include line breaks. |
|
list_of_words = [] |
|
for l in re.sub(" +", " ", text).split("\n"): |
|
line_as_list = l.split() |
|
list_of_words.extend(line_as_list) |
|
list_of_words.append("\n") |
|
|
|
# Initialise, then iterate over the list of words, preserving its |
|
# index value for later checking. |
|
line_length = 0 |
|
line = "" |
|
for index, s in enumerate(list_of_words): |
|
|
|
# If the current word does not take us over the usable length, |
|
# append it to the current line. But first check for it being a |
|
# newline. |
|
if s == "\n": |
|
ready_to_print = True |
|
elif line_length + 1 + len(s) <= usable_text_length: |
|
|
|
# Handle the first word in a line differently from all the others |
|
line = line + s if line == "" else line + " " + s |
|
line_length = len(line) |
|
ready_to_print = False |
|
else: |
|
ready_to_print = True |
|
|
|
# If the above section completed a line; or if the current word is the |
|
# last one; or if the current line plus the NEXT word will take us |
|
# over the usable length; then print the line. Having printed, |
|
# reset the initial values. |
|
if (ready_to_print or |
|
index == len(list_of_words) - 1 or |
|
line_length + 1 + len(list_of_words[index + 1]) |
|
> usable_text_length): |
|
print("* {} *".format(line.ljust(usable_text_length))) |
|
line_length = 0 |
|
line = "" |
|
|
|
print(BLANK) |
|
print(STARS) |
|
print() |