Simple string formatting question

Paul McGuire ptmcg at austin.rr._bogus_.com
Thu Apr 6 08:46:01 EDT 2006


"Fredrik Lundh" <fredrik at pythonware.com> wrote in message
news:mailman.4181.1144326919.27775.python-list at python.org...
> 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







More information about the Python-list mailing list