"Fredrik Lundh" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > Steven D'Aprano wrote: > > > Here is a (quick and dirty) reference implementation: > > > > def format(f, width=3): > > fs = '%%.%df' % width > > s = fs % f > > return s.rstrip('0').rstrip('.') > > > > Is there a way of getting the same result with just a > > single string format expression? > > not with % itself, but you can do it all in one line: > > def format(f, width=3): return ("%.*f" % (width, f)).rstrip(".0") > > </F> > > > Ooops, don't combine the two calls to rstrip().
def format(f, width=3): return ("%.*f" % (width, f)).rstrip(".0") print format(3.140) print format(3.000) print format(3.0000001) print format(30.0000) print format(300000.000) Gives: 3.14 3 3 3 3 But this works fine: def format(f, width=3): return ("%.*f" % (width, f)).rstrip("0").rstrip(".") -- Paul -- http://mail.python.org/mailman/listinfo/python-list