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

wesley chun wescpy at gmail.com
Thu May 29 10:56:55 CEST 2008


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.

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 ( ).

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


More information about the Python-3000 mailing list