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

This is what you want:

for i in range(len(job_IDs)):
    print "Job {item:15} {value[0]:>6}.{value[1]:<6} {units:3}".format(item=job_IDs[i]+':', value=memory_used[i].split('.') if '.' in memory_used[i] else (memory_used[i], '0'), units=memory_units[i])

Here is how it works:

This is the main part: value=memory_used[i].split('.') if '.' in memory_used[i] else (memory_used[i], '0'), which means: if there is a decimal point, split the string as the whole and decimal part, or set the decimal part to 0.

Then in the format string: {value[0]:>6}.{value[1]:<6} means, the whole part shifted right, followed by a dot, then the decimal part shifted left.

which prints:

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

Leave a Comment