Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 849
WilliamKF Avatar asked Nov 07 '12 20:11

WilliamKF


People also ask

How do you print capitalized hex in Python?

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 .

How do you get upper case letters in Python?

To check if a character is upper-case, we can simply use isupper() function call on the said character.

Does hexadecimal use uppercase or lowercase?

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.


4 Answers

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}")
like image 187
Eric Avatar answered Oct 11 '22 19:10

Eric


Just use upper().

intNum = 1234
hexNum = hex(intNum).upper()
print('Upper hexadecimal number = ', hexNum)

Output:

Upper hexadecimal number =  0X4D2
like image 44
nimesh Avatar answered Oct 11 '22 19:10

nimesh


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).

like image 5
jsbueno Avatar answered Oct 11 '22 19:10

jsbueno


print(hex(value).upper().replace('X', 'x'))

Handles negative numbers correctly.

like image 5
Simon Lindholm Avatar answered Oct 11 '22 19:10

Simon Lindholm