How do I convert a single character into it's hex ascii value in python

IamPolaris picture IamPolaris · Nov 11, 2011 · Viewed 137.8k times · Source

I am interested in taking in a single character,

c = 'c' # for example
hex_val_string = char_to_hex_string(c)
print hex_val_string

output:

63

What is the simplest way of going about this? Any predefined string library stuff?

Answer

Sven Marnach picture Sven Marnach · Nov 11, 2011

To use the hex encoding in Python 3, use

>>> import codecs
>>> codecs.encode(b"c", "hex")
b'63'

In legacy Python, there are several other ways of doing this:

>>> hex(ord("c"))
'0x63'
>>> format(ord("c"), "x")
'63'
>>> "c".encode("hex")
'63'