Simple string formatting question

Steven D'Aprano steve at REMOVEMEcyber.com.au
Thu Apr 6 05:18:36 EDT 2006


I have a sinking feeling I'm missing something really, 
really simple.

I'm looking for a format string similar to '%.3f' 
except that trailing zeroes are not included.

To give some examples:

Float        String
1.0          1
1.1          1.1
12.1234      12.123
12.0001      12

and similar.

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?



-- 
Steven




More information about the Python-list mailing list