按特定顺序格式化字符串

时间:2011-08-11 15:24:19

标签: python string

我正在尝试制作一个这样的简单布局:

---------
-       -
-  ABC  -
-       -
---------

我尝试了两种方法但失败了: 第一种方法:将光标放在正确的位置,但我似乎无法将第二条垂直线放在我想要的位置:

    # making first horizontal linefrom position 00
    string_line = "-"*width              
    position00 = 0
    self.summarylines.append(string_line.ljust(position00))

    # making first vertical line from position 00
    for i in range(height):
            self.summarylines.append('-')

    # making second horizontal line from position V0
    poistion0V=position00+height        
    self.summarylines.append(string_line.ljust(poistion0V))

    # making second vertical line from position H0
    positionH0 = position00+width
    for i in range(height):
            self.summarylines.append('-'.ljust(positionH0))

第二种方法:通过在它们之间添加空格来同时添加两条垂直线:

    # making first horizontal linefrom position 00
    string_line = "-"*width              
    position00 = 0
    self.summarylines.append(string_line.ljust(position00))

    # making first and second vertical line from position 00 + H0
    for i in range(height):
            self.summarylines.append('-    -')

    # making second horizontal line from position V0
    poistion0V=position00+height        
    self.summarylines.append(string_line.ljust(poistion0V))

然而,对于这种情况,我不知道如何添加与水平线的宽度一样大的正确空间。 无论哪种方式,我都没有成功使其中任何一个工作。 提前谢谢。

1 个答案:

答案 0 :(得分:3)

>>> foo = 'ABC'
>>> head = ['-' * (len(foo)+6), '-%s-' % (' '*(len(foo)+4))]
>>> print '\n'.join(head + ['-  %s  -' % foo] + head[::-1])
---------
-       -
-  ABC  -
-       -
---------