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 |
+--------+
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With