Printing Lists as Tabular Data

后端 未结 14 2078
小蘑菇
小蘑菇 2020-11-21 06:38

I am quite new to Python and I am now struggling with formatting my data nicely for printed output.

I have one list that is used for two headings, and a matrix that

14条回答
  •  遥遥无期
    2020-11-21 07:22

    Python actually makes this quite easy.

    Something like

    for i in range(10):
        print '%-12i%-12i' % (10 ** i, 20 ** i)
    

    will have the output

    1           1           
    10          20          
    100         400         
    1000        8000        
    10000       160000      
    100000      3200000     
    1000000     64000000    
    10000000    1280000000  
    100000000   25600000000
    1000000000  512000000000
    

    The % within the string is essentially an escape character and the characters following it tell python what kind of format the data should have. The % outside and after the string is telling python that you intend to use the previous string as the format string and that the following data should be put into the format specified.

    In this case I used "%-12i" twice. To break down each part:

    '-' (left align)
    '12' (how much space to be given to this part of the output)
    'i' (we are printing an integer)
    

    From the docs: https://docs.python.org/2/library/stdtypes.html#string-formatting

提交回复
热议问题