In Python v2.6 I can get hexadecimal for my integers in one of two ways:
print(("0x%x")%value)
print(hex(value))
However, in both cases, the hexadecimal digits are lower case. How can I get these in upper case?
Using %x conversion If you use %#x , the hexadecimal literal value is prefixed by 0x . To get an uppercase hexadecimal string, use %X or %#X .
To check if a character is upper-case, we can simply use isupper() function call on the said character.
Hexadecimal, however, is traditionally written in uppercase, so maybe I'm - strictly speaking - in the 'wrong'. People recognize letters and digits mainly by how the top part looks, so it makes more sense to use all uppercase.
Capital X (Python 2 and 3 using sprintf-style formatting):
print("0x%X" % value)
Or in python 3+ (using .format
string syntax):
print("0x{:X}".format(value))
Or in python 3.6+ (using formatted string literals):
print(f"0x{value:X}")
Just use upper().
intNum = 1234
hexNum = hex(intNum).upper()
print('Upper hexadecimal number = ', hexNum)
Output:
Upper hexadecimal number = 0X4D2
By using uppercase %X
:
>>> print("%X" % 255)
FF
Updating for Python 3.6 era: Just use 'X' in the format part, inside f-strings:
print(f"{255:X}")
(f-strings accept any valid Python expression before the :
- including direct numeric expressions and variable names).
print(hex(value).upper().replace('X', 'x'))
Handles negative numbers correctly.
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