如何配置ipython以十六进制格式显示整数?

17 投票
2 回答
3182 浏览
提问于 2025-04-17 16:29

这是默认的行为:

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

而我想要的是这样的:

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

我可以设置ipython来实现这个吗?

2 个回答

5

根据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
26

你可以通过注册一个特别的显示格式来处理整数:

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

这样每次你启动 IPython 时,这段代码都会被执行。

撰写回答