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?
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?
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.
formatter.for_type(int, lambda n, p, cycle: p.text("%d (0x%X)" % (n,n)))
hex(...)
to get results in hex format.
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.
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