ipython:用千位分隔符打印数字

我使用ipython 5.8.0Debian 10

这是输出的样子:

In [1]: 50*50
Out[1]: 2500

是否可以配置ipython为使用千位分隔符打印所有数字?IE:

In [1]: 50*50
Out[1]: 2'500

In [2]: 5000*5000
Out[2]: 25'000'000

也许,是否有可能ipython在输入时也理解千位分隔符?

In [1]: 5'000*5'000
Out[1]: 25'000'000

更新

接受的答案@Chayim Friedman适用于整数,但不适用于浮点数:

In [1]: 500.1*500
Out[1]: 250050.0

此外,当它工作时,它,用作千位分隔符的字符:

In [1]: 500*500
Out[1]: 250,000

我可以用'吗?

回答

'在输入中使用千位分隔符是非常有问题的,因为 Python 用于'分隔字符串,但您可以使用_(PEP 515,数字文字中的下划线):

关于输出,这有点困难,但可以使用 IPython 扩展来完成。

将以下 Python 代码放在 ~/.ipython/extensions/thousands_separator.py 的新文件中:

default_int_printer = None

def print_int(number, printer, cycle):
    printer.text(f'{number:,}') # You can use `'{:,}'.format(number)` if you're using a Python version older than 3.6

def load_ipython_extension(ipython):
    global default_int_printer

    default_int_printer = ipython.display_formatter.formatters['text/plain'].for_type(int, print_int)

def unload_ipython_extension(ipython):
    ipython.display_formatter.formatters['text/plain'].for_type(int, default_int_printer)

此代码告诉 IPython 将默认int格式化程序替换为在加载此扩展时打印千位分隔符的格式化程序,并在卸载时恢复原始格式化程序。

编辑:如果你想有一个不同的分隔符,例如',更换f'{number:,}'f'{number:,}'.replace(',', "'")

您可以使用魔术命令加载扩展并使用%load_ext thousands_separator卸载它%unload_ext thousands_separator,但如果您总是想要它,您可以将它放在默认配置文件中。

在终端中运行以下代码:

ipython3 profile create
ipython3 profile create

它将报告创建了一个文件 ~/.ipython/profile_default/ipython_config.py。输入它,然后搜索以下字符串:

将其替换为以下内容:

## A list of dotted module names of IPython extensions to load.
#c.InteractiveShellApp.extensions = []

这告诉 IPython 默认加载这个扩展。

完毕!

编辑:我看到你想 a)'用作分隔符,b) 对浮点数做同样的事情:

使用不同的分隔符非常简单:只需str.replace()

# A list of dotted module names of IPython extensions to load.
c.InteractiveShellApp.extensions = [
    'thousands_separator'
]

对浮点数做同样的事情也很简单:只需设置print_int它就可以将浮点数打印到。我还建议将名称更改为print_number.

最终代码:

def print_int(number, printer, cycle):
    printer.text(f'{number:,}'.replace(',', "'"))


以上是ipython:用千位分隔符打印数字的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>