Python-创建具有动态大小的文本边框

jts*_*287 4 python command-line border

我正在创建一个命令行脚本,我希望有一个盒子...

+--------+
|        |
|        |
|        |
+--------+
Run Code Online (Sandbox Code Playgroud)

...将永远适合其内容。我知道怎么做顶部和底部,但是它使杠杆和杠杆正确工作。每行可能有一个字符串替换项,或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    |
+--------+
Run Code Online (Sandbox Code Playgroud)

Eya*_*vin 6

你可以这样做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)
Run Code Online (Sandbox Code Playgroud)

输出:

+-----------------------+
| some words that       |
| could be dynamic but  |
| are currently static  |
+-----------------------+
Run Code Online (Sandbox Code Playgroud)


Bun*_*nyk 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)
Run Code Online (Sandbox Code Playgroud)

因此,您首先将所有对象格式化为可text警告的,然后将其传递给bordered()函数。