Python 3.4.3对齐列

时间:2015-07-27 03:48:39

标签: python

如何将aList(字母)与列对齐?此外,如果我将列增加到更低或更高的量,我将如何调整aList,如果用户输入一定数量的列,则字母将与网格的其余部分对齐?

aList = ['A','B','C','D','E','F','G','H','I','J']
bList = len(aList)
grid = []
aWidth = 10
aHeight = 10

def garden(grid):
    for j in range(0, bList):
        print(" ", aList[j], end = '')
    print( )

    for i in range(aWidth):
        if i+1 < 10:
            print(i+1, '', end=' ')
        else:
            print(i+1, end=' ')
        for j in range(aHeight):
                print('- ', end=' ')  
        else:
            print('\n',end='')

#Main            
garden(grid)

输出就是这个

  A  B  C  D  E  F  G  H  I  J
1  -  -  -  -  -  -  -  -  -  -  
2  -  -  -  -  -  -  -  -  -  -  
3  -  -  -  -  -  -  -  -  -  -  
4  -  -  -  -  -  -  -  -  -  -  
5  -  -  -  -  -  -  -  -  -  -  
6  -  -  -  -  -  -  -  -  -  -  
7  -  -  -  -  -  -  -  -  -  -  
8  -  -  -  -  -  -  -  -  -  -  
9  -  -  -  -  -  -  -  -  -  -  
10 -  -  -  -  -  -  -  -  -  - 

期望的输出

   A  B  C  D  E  F  G  H  I  J
1  -  -  -  -  -  -  -  -  -  -  
2  -  -  -  -  -  -  -  -  -  -  
3  -  -  -  -  -  -  -  -  -  -  
4  -  -  -  -  -  -  -  -  -  -  
5  -  -  -  -  -  -  -  -  -  -  
6  -  -  -  -  -  -  -  -  -  -  
7  -  -  -  -  -  -  -  -  -  -  
8  -  -  -  -  -  -  -  -  -  -  
9  -  -  -  -  -  -  -  -  -  -  
10 -  -  -  -  -  -  -  -  -  - 

感谢任何可以帮助我的回复。

2 个答案:

答案 0 :(得分:0)

如果您希望列具有特定宽度,则string.format可以提供帮助。如果您希望将变量放在一个特定宽度的列中,只需执行:

'{:3}'.format(22)
#' 22'

如果你想让它保持对齐,只需添加一个&#39;&lt;&#;,例如:

'{:<3}'.formatt(22)
#'22 '

答案 1 :(得分:0)

如何使用str.center()函数使数据位于固定宽度的中心,并指定静态列宽,以便所有列都那么大?

演示 -

invertTree

结果 -

aList = ['A','B','C','D','E','F','G','H','I','J']
bList = len(aList)
grid = []
aWidth = 10
aHeight = 10

def garden(grid):
    colWidth=5
    print(" "*colWidth,end='') #This is needed as first column does not have a title.
    for j in range(0, bList):
        print(aList[j].center(colWidth), end = '')
    print( )
    for i in range(aWidth):
        if i+1 < 10:
            print(str(i+1).center(colWidth), end='')
        else:
            print(str(i+1).center(colWidth), end='')
        for j in range(aHeight):
                print('-'.center(colWidth), end='')  
        else:
            print('\n',end='')

#Main            
garden(grid)