Python - Create a text border with dynamic size

Viewed 13397

I'm creating a command line script and I'd like there to be box...

+--------+
|        |
|        |
|        |
+--------+

... that will always fit its contents. I know how to do the top and bottom, but it's getting the ljust and rjust working correctly. There may be one string substitute per line, or 5, and the len of those strings could be anything between 0 and 80.

I have been doing things like:

print "|%s|" % (my_string.ljust(80-len(my_string)))

But holy dang is that messy... And that's just one hardcoded substitution. I have no idea how to make it dynamic with say 2 subs on line one, and 3 subs on line two and 1 sub on line three (all this in a column format).

So for a basic example, I need:

+--------+
| 1      |
| 1 2 3  |
| 1 2    |
+--------+
5 Answers

You can do it with tabulate

from tabulate import tabulate

text = """
some words that
could be dynamic but 
are currently static
"""

table = [[text]]
output = tabulate(table, tablefmt='grid')

print(output)

Output:

+-----------------------+
| some words that       |
| could be dynamic but  |
| are currently static  |
+-----------------------+
Related