Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Create a text border with dynamic size

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    |
+--------+
like image 401
jtsmith1287 Avatar asked Dec 08 '22 10:12

jtsmith1287


1 Answers

I do it like this:

def bordered(text):
    lines = text.splitlines()
    width = max(len(s) for s in lines)
    res = ['┌' + '─' * width + '┐']
    for s in lines:
        res.append('│' + (s + ' ' * width)[:width] + '│')
    res.append('└' + '─' * width + '┘')
    return '\n'.join(res)

So you first format all your objects into text wariable, and then pass it throught bordered() function.

like image 157
Bunyk Avatar answered Dec 11 '22 10:12

Bunyk