17

Here's the default behavior:

In [21]: 255
Out[21]: 255

And here's what I would like:

In [21]: 255
Out[21]: FF

Can I setup ipython to do that?

2

2 Answers 2

26

You can do this by registering a special display formatter for ints:

In [1]: formatter = get_ipython().display_formatter.formatters['text/plain']

In [2]: formatter.for_type(int, lambda n, p, cycle: p.text("%X" % n))
Out[2]: <function IPython.lib.pretty._repr_pprint>

In [3]: 1
Out[3]: 1

In [4]: 100
Out[4]: 64

In [5]: 255
Out[5]: FF

If you want this always-on, you can create a file in $(ipython locate profile)/startup/hexints.py with the first two lines (or as one to avoid any assignments):

get_ipython().display_formatter.formatters['text/plain'].for_type(int, lambda n, p, cycle: p.text("%X" % n))

which will be executed every time you start IPython.

4
  • 2
    Even better: print both representations! formatter.for_type(int, lambda n, p, cycle: p.text("%d (0x%X)" % (n,n)))
    – mbauman
    Aug 16, 2013 at 21:50
  • This suggestion is awesome, will save me cumulative hours of typing hex(...) to get results in hex format.
    – wump
    Jan 22, 2017 at 10:22
  • What does cycle do in the lambda definition?
    – wjandrea
    Jun 9, 2017 at 15:36
  • I tried removing cycle, got an error, and looked at the relevant source code. It seems it's irrelevant in this case, but has something to do with printing iterables.
    – wjandrea
    Jun 21, 2017 at 19:00
5

Based on minrk's answer and rjb's answer on another question, I put this in my Python startup file:

def hexon_ipython():
  '''To print ints as hex, run hexon_ipython().
  To revert, run hexoff_ipython().
  '''
  formatter = get_ipython().display_formatter.formatters['text/plain']
  formatter.for_type(int, lambda n, p, cycle: p.text("0x%x" % n))


def hexoff_ipython():
  '''See documentation for hexon_ipython().'''
  formatter = get_ipython().display_formatter.formatters['text/plain']
  formatter.for_type(int, lambda n, p, cycle: p.text("%d" % n))


hexon = hexon_ipython
hexoff = hexoff_ipython

So I can use it like this:

In [1]: 15
Out[1]: 15

In [2]: hexon()

In [3]: 15
Out[3]: 0xf

In [4]: hexoff()

In [5]: 15
Out[5]: 15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.