Simple string formatting question

Peter Otten __peter__ at web.de
Fri Apr 7 09:57:42 EDT 2006


Steven D'Aprano wrote:

> 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?

Does it have to be a string or can you cheat? If so:

>>> class Format(str):
...     def __new__(cls, width):
...             return str.__new__(cls, "%%.%df" % width)
...     def __mod__(self, other):
...             return str.__mod__(self, other).rstrip("0").rstrip(".")
...
>>> format = Format(3)
>>> for f in [1.0, 1.1, 12.1234, 12.0001]:
...     print f, "-->", format % f
...
1.0 --> 1
1.1 --> 1.1
12.1234 --> 12.123
12.0001 --> 12

For passing around in your app that should be as convenient as a string --
of course it will break if you store the "format" in a file, say.

Peter



More information about the Python-list mailing list