问题
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?
回答1:
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}")
回答2:
Just use upper().
intNum = 1234
hexNum = hex(intNum).upper()
print('Upper hexadecimal number = ', hexNum)
Output:
Upper hexadecimal number = 0X4D2
回答3:
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).
回答4:
print(hex(value).upper().replace('X', 'x'))
Handles negative numbers correctly.
回答5:
The more Python 3 idiom using f-strings would be:
value = 1234
print(f'0x{value:X}')
'0x4D2'
Notes (and why this is not a duplicate):
- shows how to avoid capitalizing the '0x' prefix, which was an issue in other answers
- shows how to get variable interpolation
f'{value}'
; nobody actually ever puts hex literals in real code. There are plenty of pitfalls in doing interpolation: it's notf'{x:value}'
norf'{0x:value}'
norf'{value:0x}'
nor evenf'{value:%x}'
as I also tried. So many ways to trip up. It still took me 15 minutes of trial-and-error after rereading four tutorials and whatsnew docs to get the syntax. This answer shows how to get f-string variable interpolation right; others don't.
来源:https://stackoverflow.com/questions/13277440/how-can-i-get-python-to-use-upper-case-letters-when-printing-hexadecimal-values