user1603472
user1603472

Reputation: 1458

How do I condition the format specifier on the value of the argument?

I would like to output the values as {:f} if they are above 0.001, say, otherwise as {:e} (exponentials).

I wonder if I can do this within one string formatting line, that is not conditioning on the line that actually prints, but inside it. Are lambda expressions permitted? (Side note: where are they permitted, really?)

FTR, this is my output string:

print("{:f}".format(my_float))

Upvotes: 3

Views: 75

Answers (2)

thiruvenkadam
thiruvenkadam

Reputation: 4260

Adding the condition into the format is one way I could think

>>> x = 0.0001276
>>> '{:{type}}'.format(x, type='f' if x>0.001 else 'e')
'1.276000e-04'
>>> x = 0.01
>>> '{:{type}}'.format(x, type='f' if x>0.001 else 'e')
'0.010000'

This is better than lambda, in my opinion.

To do away with if else, you can go with and or operation

(x>0.01 and 'f') or 'e'

Upvotes: 2

mgilson
mgilson

Reputation: 310117

I think I'd use "{:g}". This will flop back and forth between exponential notation and normal float notation depending on the value:

>>> '{:g}'.format(0.001)
'0.001'
>>> '{:g}'.format(0.0000001)
'1e-07'

In contrast to "{:e}" which is always exponential...

>>> '{:e}'.format(0.001)
'1.000000e-03'

Upvotes: 2

Related Questions