I am trying to get the results of my list calculations to display in an orderly fashion by formatting the print() function. I have tried various methods from this site and Python Docs.
The closest that I can get it to display in a table like format is to align the output using the .format() function, but a couple of the lines are still offset. I understand that this is because the preceding results are longer than the others, but I can't figure out a way to get the text to align in columns.
When I try to amend the string formatting from what I already have I get a "tuple index out of range" error. But as far as I am aware I'm not using Tuples?
This is the string I am trying to print:
print('{:<10}'.format("Richter Scale Value:"), '{:<10}'.format(rVal),'{:^10}'.format ("Joules:"),'{:^10}'.format(joules),'{:>10}'.format("TNT:"),'{:>10}'.format(tnt))
But the output I get is:
Richter Scale Value: 1 Joules: 1995262.3149688789 TNT: 0.00047687913837688307
Richter Scale Value: 5 Joules: 1995262314968.8828 TNT: 476.87913837688404
Richter Scale Value: 9.1 Joules: 2.818382931264449e+18 TNT: 673609687.2046962
Richter Scale Value: 9.2 Joules: 3.981071705534953e+18 TNT: 951498973.5982201
Richter Scale Value: 9.5 Joules: 1.1220184543019653e+19 TNT: 2681688466.3048882
I can't figure out how to get the last three 'TNT' lines to match up.
This is the code preceding the print():
rVal = 0
qList=[1,5,9.1,9.2,9.5]
qList_len = len(qList)
for i in range (0,qList_len):
rVal = qList[i]
joules = 10**((1.5*rVal)+4.8)
tnt = joules/(4.184*10**9)
Any assistance will be gratefully received thanks.
You need to explicitly format your joules
values a precision. You have only given a minimum width, but the default format exceeds that:
print('Richter Scale Value: {:<10.1f} Joules: {:<10.8g} TNT: {:10.8g}'.format(
rVal, joules, tnt))
You may want to tweak the exact widths and how many decimals are displayed. You also could use f
instead of g
to always force displaying the values without scientific e
notation, or use e
to force scientific notation instead.
I combined your 6 str.format()
calls into one. There is little point in formatting constant label strings.
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加