Using Python's Format Specification Mini-Language to align floats

前端 未结 4 2022
陌清茗
陌清茗 2020-12-03 07:44

I read that I can use Python\'s Format Specification Mini-Language to have more control over how strings are displayed. However, I am having a hard time figuring out how to

4条回答
  •  庸人自扰
    2020-12-03 08:19

    Here's another implementation based on .split('.') idea. It might be more readable. Split on '.', right-align the left part, left-align the right part:

    width = max(map(len, job_IDs)) # width of "job id" field 
    for jid, mem, unit in zip(job_IDs, memory_used, memory_units):
      print("Job {jid:{width}}: {part[0]:>3}{part[1]:1}{part[2]:<3} {unit:3}".format(
        jid=jid, width=width, part=str(mem).partition('.'), unit=unit))
    

    Output

    Job 13453 :  30     MB 
    Job 123   : 150.54  GB 
    Job 563456:  20.6   MB 
    

提交回复
热议问题