打印变量标题

时间:2013-12-04 14:47:23

标签: python

当字符串的长度发生变化时,我想打印这些标题以获得更长/更短的标题。我不知道如何做到这一点,我想我可以使用len()并根据它们的长度打印一些“=”,但它没有按预期结束。

+==========================+
| Running: hba_test
| Skipping: abort/"Basic Sanity" delayedabort/"Abort Control List"
+==========================+
+==========================+
| Skipping: sdt_test
+==========================+

这些是标题,这是当前用于生成它们的代码。

    #print header to seperate tests
    l1 = len(x)
    l2 = len(y)

    print "+==========================+"
    if disable:
        print "| Skipping: %s " % x
    else:
        print "| Running: %s " % x
        if 'disable=' in test:
           print "| Skipping:%s " % y 
    print "+==========================+"

2 个答案:

答案 0 :(得分:1)

这可能有所帮助:

如果您知道要打印多少=,可以执行以下操作:

In [2]: "=" * 50
Out[2]: '=================================================='

答案 1 :(得分:1)

这些方面的内容怎么样?它虽然不优雅且“硬编码”。

使用原始代码:

x = 'hba_test'
y = 'abort/"Basic Sanity" delayedabort/"Abort Control List"'
disable = False
test = 'disable='

#print header to seperate tests
l1 = len(x)
l2 = len(y)


if disable:
    headerBreak ="+" + "="*(l1+12) + "+"
    print headerBreak
    print "| Skipping: %s |" % x
else:
    headerBreak =  "+" + "="*(max(l1,l2)+11) + "+"
    print headerBreak
    print "| Running: %s" % x, ' '*(l2-l1)+ '|'
    if 'disable=' in test:
       print "| Skipping:%s |" % y 
print headerBreak

返回:

+=================================================================+
| Running: hba_test                                               |
| Skipping:abort/"Basic Sanity" delayedabort/"Abort Control List" |
+=================================================================+

+====================+
| Skipping: hba_test |
+====================+

使用函数:

x = 'hba_test'
y = 'abort/"Basic Sanity" delayedabort/"Abort Control List"'
disable = False
test = 'disable='

#print header to seperate tests
def asciiBlock(lineList):
    maxLength = 0
    lines = []
    for line in lineList:
        newLine = ': '.join(line)
        lines.append(newLine)
        if maxLength<len(newLine):
            maxLength=len(newLine)


    asciiArt = '+'+'='*(maxLength+2)+'+'
    newLineList = [asciiArt]
    for line in lines:
        newLineList.append('| '+ line + ' '*(maxLength-len(line))+' |')

    newLineList.append(asciiArt)

    return '\n'.join(newLineList)


if disable:
    lineList = [('Skipping',x)]

else:
    lineList = [('Running',x)]
    if 'disable=' in test:
        lineList.append(('Skipping',y))

print asciiBlock(lineList)
相关问题