这是默认行为:
In [21]: 255
Out[21]: 255
以下是我想要的内容:
In [21]: 255
Out[21]: FF
我能设置IPython来做到这一点吗?
您可以通过为整数注册特殊的显示格式化程序来实现此操作:
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
如果想要让这个功能一直开启,可以在 $(ipython locate profile)/startup/hexints.py
中创建一个文件,并添加以下两行代码(或者合并为一行以避免任何赋值):
get_ipython().display_formatter.formatters['text/plain'].for_type(int, lambda n, p, cycle: p.text("%X" % n))
formatter.for_type(int, lambda n, p, cycle: p.text("%d (0x%X)" % (n,n)))
- mbaumancycle
是什么作用? - wjandrea基于 minrk的回答和rjb的回答在另一个问题上, 我将以下内容放入我的Python启动文件:
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
那么我可以像这样使用它:
In [1]: 15
Out[1]: 15
In [2]: hexon()
In [3]: 15
Out[3]: 0xf
In [4]: hexoff()
In [5]: 15
Out[5]: 15