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

前端 未结 4 2021
陌清茗
陌清茗 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:23

    This does it:

    import re
    
    job_IDs = ['13453', '123', '563456']
    memory_used = ['30', '150.54', '20.6']
    memory_units = ['MB', 'GB', 'MB']
    
    for i in range(len(job_IDs)):
        lh=re.match(r'(\d+)',memory_used[i]).group(1)
        if '.' in memory_used[i]:
            rh=re.match(r'(\d+)\.(\d+)',memory_used[i]).group(2)
            sep='.'
        else:
            rh=''    
            sep=' '
    
    
        my_str = "{item:15}{l:>6}{s:1}{r:6} {units:3}".format( 
        item='Job ' + job_IDs[i] + ':' , l=lh,s=sep,r=rh,units=memory_units[i])
    
        print my_str
    

    To get your precise out put, you need to break the strings on the optional '.'

    You could also convert those strings to floats.

提交回复
热议问题