16

デフォルトの動作は次のとおりです。

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

そして、これが私が欲しいものです:

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

それを行うためにipythonをセットアップできますか?

4

2 に答える 2

25

これを行うには、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、最初の2行で(または割り当てを避けるために1行として)ファイルを作成できます。

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

これは、IPythonを起動するたびに実行されます。

于 2013-02-21T02:27:18.803 に答える
3

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
于 2017-06-08T03:49:56.057 に答える