Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
821 views
in Technique[技术] by (71.8m points)

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

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 use it to display floats aligned on the decimal point.

For example, say I have thre following three lists:

job_IDs = ['13453', '123', '563456'];
memory_used = [30, 150.54, 20.6];
memory_units = ['MB', 'GB', 'MB'];

I would like to iterate through these three lists and print

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

So far I have tried:

for i in range(len(jobIDs)):
   my_str = "{item:15}{value:6} {units:3}".format( 
   item='Job ' + job_IDs[i] + ':' , value=str(memories[i]),units=memory_units[i]);

   print my_str

which prints:

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

which is almost right, but it does not align the floats around the decimal point. How can I use Python's Format Specification Mini-Language to do it the way I need?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...