[英]How can I configure ipython to display integers in hex format?
這是默認行為:
In [21]: 255
Out[21]: 255
這就是我想要的:
In [21]: 255
Out[21]: FF
我可以設置ipython嗎?
您可以通過為int注冊特殊的顯示格式化器來完成此操作:
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時都會執行。
基於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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.