Python-创建具有动态大小的文本边框 [英] Python - Create a text border with dynamic size

查看:64
本文介绍了Python-创建具有动态大小的文本边框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个命令行脚本,并且希望有框...

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

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

...将始终适合其内容.我知道怎么做顶部和底部,但是它可以使平衡杆和平衡杆正常工作.每行可能有一个字符串替换项,或5,并且这些字符串的len可以是0到80之间的任何值.

... 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:

<代码>打印"|%s |"%(my_string.ljust(80-len(my_string)))

但是,当当真是一团糟……而这仅仅是一个硬编码的替代品.我不知道如何通过第一行的2个subs,第二行的3个subs和第三行的1个subs来使其动态化(所有这些都以列格式).

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    |
+--------+

推荐答案

我这样做是这样的:

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()函数.

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

这篇关于Python-创建具有动态大小的文本边框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆