I am attempting to use the #X
format specifier to print a hexadecimal value using capital letters for the "digits" while automatically prepending the usual 0x
prefix. For example, decimal 10
should be represented as 0xA
.
However, that specifier does not seem to behave in that way:
>>> print(f'{10:#X}')
0XA
>>> '{:#X}'.format(10)
'0XA'
Which looks like the X
modifier makes the whole string representation of the number (including the 0x
prefix) go through str.upper
instead of the "number part" only. I thought that was fair enough but, after checking the Format Specification Mini-Language, it looks like it might not be the intended result (or, at least, it is not clearly documented). Here are the relevant bits:
The
'#'
option causes the "alternate form" to be used for the conversion. [...] For integers, when [...] hexadecimal output is used, this option adds the prefix [...]'0x'
to the output value.[...]
The available integer presentation types are:
Type Meaning [...] [...] 'x'
Hex format. Outputs the number in base 16, using lower-case letters for the digits above 9. 'X'
Hex format. Outputs the number in base 16, using upper-case letters for the digits above 9. [...] [...]
And this seems to imply that upper-case letters should only be for non-decimal hexadecimal digits (a
, b
, c
, d
, e
, f
) and therefore should not concern x
(from 0x
); is that right?
Should comes first in the verb phrase (after the subject and before another verb): I should go home now. Should cannot be used with another modal verb: It should probably be sunny at that time of year.
The negative form of should is shouldn't. We don't use don't, doesn't, didn't with should: There shouldn't be many people at the beach today.
To show obligation, give recommendation or even an opinion “You should stop eating fast food.” “You should go for walks more often.” “We should go to the park tomorrow.” “He should go to the pharmacy first thing in the morning.”
In formal English, should can be used with I or we in conditional clauses, instead of the more common would. This form is usually, but not always, found together with an if clause. I should love to visit Peru if I had the money. I should be very cross if they didn't give me a certificate.
As you already noticed, #X makes everything uppercase and #x makes everything lowercase. If you want the 0x to be lower and the rest uppercase then you could try something like this:
# will print 0xA
print(f'{10:#X}'.replace('0X', '0x'))
In my opionion capitalizing the x in 0x is dumb and they shouldnt have implemented it this way, but it is what it is...
edit: You can remove the # and then it will remove the 0x entirely, you can then add the 0x manually in the format string, this is the best way in my opinion:
print(f"0x{10:X}")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With