HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Print list items in a rectangular frame

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
itemsprintrectangularlistframe

Problem

The aim is to have that:

list ["Hello", "World", "in", "a", "frame"]


And make it printed like this:

*****
Hello
World
in
a
frame
*****


I did this and it works fine:

a = 0
for nb in listA:
if a == 0:
print(""10).center(20)
a += 1
if len(nb) == 2:
print(" " + nb + " ").center(20)
elif len(nb) == 1:
print(" " + nb + " ").center(20)
else:
print(" " + nb + " ").center(20)
if a == len(listA):
listA[-1]
print(""10).center(20)


Still, I feel it is very cumbersome. Do you have any ideas how I can improve it, please?

Solution

You can let .format() do most of the work for you:

def print_in_a_frame(*words):
    size = max(len(word) for word in words)
    print('*' * (size + 4))
    for word in words:
        print('* {:>> print_in_a_frame("Hello", "World", "in", "a", "frame")
*********
* Hello *
* World *
* in    *
* a     *
* frame *
*********


Most of the magic happens in this line:

print('* {:<{}} *'.format(word, size))


It may be easier to understand what's going on if we rewrite it as:

print('* {a:<{b}} *'.format(a=word, b=size))


This tells format to print the keyword argument a, left-aligned, on a field of total width the keyword argument b. Note that if b was fixed, say to 10, you would write that as:

print('* {a:<10}} *'.format(a=word))


or:

print('* {:<10}} *'.format(word))

Code Snippets

def print_in_a_frame(*words):
    size = max(len(word) for word in words)
    print('*' * (size + 4))
    for word in words:
        print('* {:<{}} *'.format(word, size))
    print('*' * (size + 4))

>>> print_in_a_frame("Hello", "World", "in", "a", "frame")
*********
* Hello *
* World *
* in    *
* a     *
* frame *
*********
print('* {:<{}} *'.format(word, size))
print('* {a:<{b}} *'.format(a=word, b=size))
print('* {a:<10}} *'.format(a=word))
print('* {:<10}} *'.format(word))

Context

StackExchange Code Review Q#128744, answer score: 8

Revisions (0)

No revisions yet.