我正在创建一个命令行脚本,我希望有一个盒子...
+--------+ | | | | | | +--------+
...将永远适合其内容。我知道怎么做顶部和底部,但是它使杠杆和杠杆正确工作。每行可能有一个字符串替换项,或5,并且这些字符串的len可以是0到80之间的任何值。
我一直在做类似的事情:
print "|%s|" % (my_string.ljust(80-len(my_string)))
但是,当当真是一团糟……而这仅仅是一种硬编码替代。我不知道如何通过第一行的2个subs和第二行的3个subs和第三行的1个subs来使其动态化(所有这些都以列格式)。
因此,对于一个基本示例,我需要:
+--------+ | 1 | | 1 2 3 | | 1 2 | +--------+
Bunyk.. 5
我这样做是这样的:
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)
因此,您首先将所有对象格式化为可text
警告的,然后将其传递给bordered()
函数。
我这样做是这样的:
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)
因此,您首先将所有对象格式化为可text
警告的,然后将其传递给bordered()
函数。