Python: Evenly space output data with varying string lengths

前端 未结 4 617
走了就别回头了
走了就别回头了 2021-01-04 14:30

I am trying to get my output data to look like this:

-------------------------------------------------------
            Grade Report for Programs 
---------         


        
4条回答
  •  醉话见心
    2021-01-04 14:48

    The answer I find easiest is just using some basic string arithmetic.

    For example, say for want the aligned a variable 20 spaces ahead of left-alignment, in your case the "average" variable, you could simply do this

    print(name_last_first + (' ' * (20-len(name_last_first))) + average
           + "<----" + grades)
    

    It's just a bit lengthier, but the code is easier to interpret in my opinion.

    (Note: this method only works with mono spaced fonts! But most Python output is defaulted to a MS font :-) )

提交回复
热议问题