python string formatting Columns in line

前端 未结 4 2050
一生所求
一生所求 2020-11-27 20:26

I am trying to format the string so everything lines up between the two.

APPLES                           $.99                           214                          


        
4条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-27 20:50

    I think the better way is auto adjust the column width from its content

    rows = [('apple', '$1.09', '80'), ('truffle', '$58.01', '2')]
    
    lens = []
    for col in zip(*rows):
        lens.append(max([len(v) for v in col]))
    format = "  ".join(["{:<" + str(l) + "}" for l in lens])
    for row in rows:
        print(format.format(*row))
    

    Output:

    apple    $1.09   80
    truffle  $58.01  2 
    

    Demo: https://code.sololearn.com/cttJgVTx55bm/#py

提交回复
热议问题