Oscar Dulzaides
Oscar Dulzaides

Reputation: 169

Python printing floating point numbers from a list

Hi I am new to programming and hav a small issue.

I have a small bit of code I am trying to print out the results from. When I print it it gives me some numbers with many decimal places and some with only one. If I try to change the placeholder from 's' to 'd' or 'f' it tell me it must be a number not a list.

Is there anyway to get this to print the numbers with 2 decimal places?

Here is the code:

ftp = 230
zones = []

def zone(n): 
    return   ftp * n

multipliers = (.55,.56,.75,.76,.85,.86,.95,.96, 1.05, 1.06, 1.20, 1.21, 1.50,1.51)

for i in (multipliers):
   zones.append(zone(i))

format = ('%-*s%*s')
header_format = '%-*s%*s'
print '=' * 65
print header_format % (45, 'Zone', 10, 'Range')
print '-' * 65

print format % (45,'Active Recovery               Below ==>> ',10, zones[:1])
print format % (45,'Endurance',10, zones[1:3])
print format % (45,'Tempo',10, zones[3:5])
print format % (45,'Sweet Spot',10, zones[5:7])
print format % (45,'Threshhold',10, zones[7:9])
print format % (45,'VO2',10, zones[9:11])
print format % (45,'Anaerobic',10, zones[11:13])
print format % (45,'Neuromuscular                 Above ==>>',5, zones[12])
print '=' * 65

Upvotes: 2

Views: 174

Answers (2)

Alex Martelli
Alex Martelli

Reputation: 882691

Yes, you just need to adjust your format string accordingly.

Right now, you have (with redundant parentheses, as you also have elsewhere, BTW):

format = ('%-*s%*s')

This format two strings with given widths and alignments -- so the lists of floats that you're getting as slices of zones will be "just stringified" with no control over formatting details.

Sometimes you're emitting a single float, sometimes two of them. It's better to use two separate format strings for the two separate purposes.

So for a single float

format1 = '%-*s%*.2f'

and for two of them

format2 = '%-*s%*.2f%*.2f'

Now, edit your various print statements accordingly, e.g the last one would become

print format1 % (45,'Neuromuscular                 Above ==>>',5, zones[12])

and the one just before it

print format2 % (45,'Anaerobic',5,zones[11],5,zones[12])

(The parentheses here are not redundant as you need a tuple on the RHS of the % operator.

BTW, the new format method of strings can be much more readable than the old % formatting operator, and I would recommend switching to it...

Upvotes: 2

Kolmar
Kolmar

Reputation: 14224

You can format the numbers separately from the rest of the string:

two_numbers_format = '(%.2f - %.2f)'

And then have:

print format % (45,'Endurance',10, two_numbers_format % zones[1:3])

And For one number:

one_number_format = '%.2f'
print format % (45,'Active Recovery               Below ==>> ',10, one_number_format % zones[:1])

Upvotes: 1

Related Questions