Bug in format specification in Python 3?

R

Robert Dailey

Hello,

According to the Python 3.1 documentation, I can have a format
specification like so:

print( 'This is a hex number: {:#08x}'.format( 4 ) )

This will print:

This is a hex number: 0x000004

I notice that the '0x' portion is counted in the width, which was
specified as 8. This seems wrong to me. Is this by design? If so, why?
I expect that the width portion to only apply to the input + padding
only. I don't consider the '0x' portion part of the padding. But maybe
it is...
 
M

MRAB

Robert said:
Hello,

According to the Python 3.1 documentation, I can have a format
specification like so:

print( 'This is a hex number: {:#08x}'.format( 4 ) )

This will print:

This is a hex number: 0x000004

I notice that the '0x' portion is counted in the width, which was
specified as 8. This seems wrong to me. Is this by design? If so, why?
I expect that the width portion to only apply to the input + padding
only. I don't consider the '0x' portion part of the padding. But maybe
it is...

The width portion is the width of what is produced by the specification.
The '#' tells it to add '0x', so that's part of what's produced. If you
don't want the '0x' to be counted then don't include '#' in the
specification. It makes perfect sense! :)
 
A

AggieDan04

Hello,

According to the Python 3.1 documentation, I can have a format
specification like so:

print( 'This is a hex number: {:#08x}'.format( 4 ) )

This will print:

This is a hex number: 0x000004

I notice that the '0x' portion is counted in the width, which was
specified as 8. This seems wrong to me. Is this by design? If so, why?
I expect that the width portion to only apply to the input + padding
only. I don't consider the '0x' portion part of the padding. But maybe
it is...

It's unintuitive to me, too, but it's the same thing that Python 2.x
did:
0x000004
 
G

greg

Robert said:
I notice that the '0x' portion is counted in the width, which was
specified as 8. This seems wrong to me. Is this by design? If so, why?

Yes, it's the total field width. This is consistent with
the other formats, in which it includes decimal points,
signs, etc.

If you don't want that, then write the format string as

'This is a hex number: 0x{:08x}'
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,020
Latest member
GenesisGai

Latest Threads

Top