How can I get Python to use upper case letters when printing hexadecimal values?

冷暖自知 提交于 2020-06-22 13:28:32

问题


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 not f'{x:value}' nor f'{0x:value}' nor f'{value:0x}' nor even f'{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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!