[Python-3000] PEP 3101 str.format() equivalent of '%#o/x/X'?

Eric Smith eric+python-dev at trueblade.com
Thu May 29 15:28:53 CEST 2008


wesley chun wrote:
> hi,
> 
> i'm looking to duplicate this string format operator '#' functionality
> with the new format(). here it is using the old string format
> operator:
> 
>>>> i = 45
>>>> 'dec: %d/oct: %o/hex: %X' % (i, i, i)         # no "#" means no leading "0" or "0x/X"
> 'dec: 45/oct: 55/hex: 2D'
>>>> 'dec: %d/oct: %#o/hex: %#X' % (i, i, i)     # leading "#" gives us "0" and "0x/X"
> 'dec: 45/oct: 0o55/hex: 0X2D'
> 
> if i repeat both of the above with format(), it fails with the "#":
> 
>>>> 'dec: {0}/oct: {0:o}/hex: {0:X}'.format(i)
> 'dec: 45/oct: 55/hex: 2D'
>>>> 'dec: {0}/oct: {0:#o}/hex: {0:#X}'.format(i)
> Traceback (most recent call last):
>   File "<pyshell#33>", line 1, in <module>
>     'dec: {0}/oct: {0:#o}/hex: {0:#X}'.format(i)
> ValueError: Invalid conversion specification
> 
> i have to resort to the uglier:
> 
>>>> 'dec: {0}/oct: 0o{0:o}/hex: 0X{0:X}'.format(i)
> 'dec: 45/oct: 0o55/hex: 0X2D'
> 
> is this functionality being dropped, or am i missing something?  i
> didn't get anything from searching the Py3000 mailing list archives. i
> couldn't find anything in either formatter.h nor stringobject.c.

I don't see it as a big problem.  You can now use any prefix you want, 
instead of the hard coded values that # supplied.

> 
> secondly, and much more minor, is that i think there's a minor typo in the PEP:
> print format(10.0, "7.3g")  <-- print() is now a function so it needs
> another pair of ( ).

Fixed in r63786.  Thanks for catching it.  There was another print() 
function already in the PEP, so clearly the intent was to be 3.0 compliant.

Eric.

> 
> thanks,
> -- wesley
> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
> "Core Python Programming", Prentice Hall, (c)2007,2001
>  http://corepython.com
> 
> wesley.j.chun :: wescpy-at-gmail.com
> python training and technical consulting
> cyberweb.consulting : silicon valley, ca
> http://cyberwebconsulting.com
> _______________________________________________
> Python-3000 mailing list
> Python-3000 at python.org
> http://mail.python.org/mailman/listinfo/python-3000
> Unsubscribe: http://mail.python.org/mailman/options/python-3000/eric%2Bpython-dev%40trueblade.com
> 



More information about the Python-3000 mailing list