String formatting (%)

Bengt Richter bokr at oz.net
Thu Apr 29 12:02:49 EDT 2004


On Wed, 28 Apr 2004 09:15:02 -0400, Peter Hansen <peter at engcorp.com> wrote:

>Pascal wrote:
>
>> Hello,
>> I've a float number 123456789.01 and, I'de like to format it like this
>> "123 456 789.01".
>> Is this possible with % character?
>
>No, as shown by http://docs.python.org/lib/typesseq-strings.html
>but you could probably use the 'locale' module instead.
>
>I suspect there's also a regular expression that could deal with
>that, but I don't want to know what it is. ;-)
>

If you are willing to use a special name mod (you can choose it), you
can get there with % and a commafy that stuffs spaces instead of commas ;-)

 >>> class Doit(dict):
 ...     def __init__(self, d): dict.__init__(self, d)
 ...     def __getitem__(self, name):
 ...         if name.startswith('cfy_'):
 ...             return commafy(self.get(name[4:],'??'))
 ...         else: return self.get(name,'??')
 ...
 >>> def commafy(val):
 ...     sign, val = '-'[:val<0], str(abs(val))
 ...     val, dec =  (val.split('.')+[''])[:2]
 ...     if dec: dec = '.'+dec
 ...     rest = ''
 ...     while val: val, rest = val[:-3], '%s %s'%(val[-3:], rest)
 ...     return '%s%s%s' %(sign, rest[:-1], dec)
 ...
 >>> x=1234
 >>> 'x: %(x)s cfy_x: %(cfy_x)s' % Doit(vars())
 'x: 1234 cfy_x: 1 234'
 >>> x=12345.678
 >>> 'x: %(x)s cfy_x: %(cfy_x)s' % Doit(vars())
 'x: 12345.678 cfy_x: 12 345.678'
 >>> x = -12345.678
 >>> 'x: %(x)s cfy_x: %(cfy_x)s' % Doit(vars())
 'x: -12345.678 cfy_x: -12 345.678'

And the OP's example:

 >>> x = 123456789.01
 >>> 'x: %(x)s cfy_x: %(cfy_x)s' % Doit(vars())
 'x: 123456789.01 cfy_x: 123 456 789.01'

Regards,
Bengt Richter



More information about the Python-list mailing list