如何打印带框的字符串

时间:2016-05-21 15:50:20

标签: python python-3.x

我想打印一个框架所有的环绕字符串。我想使用从185到188和从200到206的ASCII字符。我想要这样的东西,但我不喜欢最后一行,因为右下方的错误对齐。它可能会变得更好吗?

retString = "\n╔══> Stanza n. %03d <══╗" % nRoom
retString += "\n╠═> Num letti: %-3d      ║" % nBeds
retString += "\n╠═> Fumatori            ║"
retString += "\n╠═> Televisione         ║"
retString += "\n╠═> Aria Condizionata  ║"
retString += "\n╚══════════════╝"
return retString

Output

1 个答案:

答案 0 :(得分:1)

不要试图手工绘制盒子。 它会破裂。

我曾经需要一些功能来绘制框,所以出于文档原因,我在这里发布了一个清理版本:

UL, UR = '╔', '╗'
SL, SR = '╠', '║'
DL, DR = '╚', '╝'
AL, AR = '═', '>'


def padded(
    line, info=None, width=42, intro='>', outro='<', filler='.', chopped='..'
):
    # cleanup input
    line = ''.join([' ', line.strip()]) if line else ''
    info = info.strip() if info else ''

    # determine available width
    width -= sum([len(intro), len(outro), len(line), len(info)])
    if width < 0:
        # chop off overflowing text
        line = line[:len(line)+width]
        if chopped:
            # place chopped characters (if set)
            chopped = chopped.strip()
            line = ' '.join([line[:len(line)-(len(chopped)+1)], chopped])

    return ''.join(e for e in [
        intro,
        info,
        line,
        ''.join(filler for _ in range(width)),
        outro
    ] if e)


def box(rnum, nbeds, *extras):
    arrow = (AL+AR)
    res = [
        # head line
        padded(
            'Stanza n. {:03d} <'.format(rnum), (AL+AL+arrow),
            intro=UL, outro=UR, filler=AL
        ),
        # first line
        padded(
            'Num letti: {:3d}'.format(nbeds), arrow,
            intro=SL, outro=SR, filler=' '
        ),
    ]
    # following lines
    res.extend(padded(e, arrow, intro=SL, outro=SR, filler=' ') for e in extras)
    # bottom line
    res.append(padded(None, None, intro=DL, outro=DR, filler=AL))

    return '\n'.join(res)


print(
    box(485, 3, 'Fumatori', 'Televisione')
)
print(
    box(123, 4, 'Fumatori', 'Televisione', 'Aria Condizionata')
)
print(
    box(1, 1, 'this is so much text it will be chopped off')
)

结果如下:

╔═══> Stanza n. 485 <════════════════════╗
╠═> Num letti:   3                       ║
╠═> Fumatori                             ║
╠═> Televisione                          ║
╚════════════════════════════════════════╝
╔═══> Stanza n. 123 <════════════════════╗
╠═> Num letti:   4                       ║
╠═> Fumatori                             ║
╠═> Televisione                          ║
╠═> Aria Condizionata                    ║
╚════════════════════════════════════════╝
╔═══> Stanza n. 001 <════════════════════╗
╠═> Num letti:   1                       ║
╠═> this is so much text it will be ch ..║
╚════════════════════════════════════════╝