如何在python解释器中控制数字格式?

时间:2021-08-11 09:20:51

I often use the python interpreter for doing quick numerical calculations and would like all numerical results to be automatically printed using, e.g., exponential notation. Is there a way to set this for the entire session?

我经常使用python解释器进行快速数值计算,并希望使用例如指数表示法自动打印所有数值结果。有没有办法为整个会话设置这个?

For example, I want:

例如,我想:

>>> 1.e12
1.0e+12

not:

>>> 1.e12
1000000000000.0

5 个解决方案

#1


Create a Python script called whatever you want (say mystartup.py) and then set an environment variable PYTHONSTARTUP to the path of this script. Python will then load this script on startup of an interactive session (but not when running scripts). In this script, define a function similar to this:

创建一个名为您想要的Python脚本(比如mystartup.py),然后将环境变量PYTHONSTARTUP设置为此脚本的路径。然后,Python将在启动交互式会话时加载此脚本(但在运行脚本时不会)。在此脚本中,定义一个类似于此的函数:

def _(v):
    if type(v) == type(0.0):
        print "%e" % v
    else:
        print v

Then, in an interactive session:

然后,在交互式会话中:

C:\temp>set PYTHONSTARTUP=mystartup.py

C:\temp>python
ActivePython 2.5.2.2 (ActiveState Software Inc.) based on
Python 2.5.2 (r252:60911, Mar 27 2008, 17:57:18) [MSC v.1310 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> _(1e12)
1.000000e+012
>>> _(14)
14
>>> _(14.0)
1.400000e+001
>>>

Of course, you can define the function to be called whaetver you want and to work exactly however you want.

当然,您可以将要调用的函数定义为所需的函数,并根据需要正确工作。

Even better than this would be to use IPython. It's great, and you can set the number formatting how you want by using result_display.when_type(some_type)(my_print_func) (see the IPython site or search for more details on how to use this).

比这更好的是使用IPython。这很棒,您可以使用result_display.when_type(some_type)(my_print_func)设置数字格式(请参阅IPython网站或搜索有关如何使用此内容的更多详细信息)。

#2


Hm... It's not a 100% solution, but this have come to my mind...

嗯...这不是100%的解决方案,但我想到了......

How about defining a subclass of float which would have an overridden __str__ method (to print with the exp notation). And then you would have to wrap all the expressions with object construction of this class). It would be a bit shorter than Dave's solution, you would define the class once and then write something like:

如何定义一个浮点的子类,它将具有重写的__str__方法(使用exp表示法打印)。然后你必须用这个类的对象构造包装所有表达式)。它会比Dave的解决方案稍短,你可以定义一次类,然后写一些类似的东西:

>>> F(1.e12)
1.0e+12
>>> F(3.)
3.0e+0
>>> F(1.+2.+3.+4.)
1.0e+1
...

#3


As you know you can use the % operator or str.format to format strings:

如您所知,您可以使用%operator或str.format格式化字符串:

For example:

>>> "%e" % 1.e12
'1.000000e+12'

I was wondering if you could monkey patch the built-in float class to change the formatting but it seems that Python won't let you:

我想知道你是否可以修补内置的float类来改变格式,但似乎Python不会让你:

>>> 1.e12.__class__.__repr__ = lambda x: "%e" % x
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can't set attributes of built-in/extension type 'float'

So the only other thing I can think of is to write your own file-like object which captures output, reformats it and sends it to the standard output. You'd then redirect standard output of the interpreter to this object:

因此,我能想到的唯一另一件事就是编写自己的类文件对象,捕获输出,重新格式化并将其发送到标准输出。然后,您将解释器的标准输出重定向到此对象:

sys.stdout = my_formatting_object

#4


Building on Dave Webb's hint above. You can of course set the precision if you like ("%.3e") and perhaps override writelines if needed.

基于Dave Webb的上述提示。您当然可以根据需要设置精度(“%。3e”),如果需要也可以覆盖writelines。

import os
import sys

class ExpFloatFileObject:
    def write(self, s):
        try:
            s = "%e"%float(s)
        except ValueError:
            pass
        sys.__stdout__.write(s)

    def __getattr__(self, name):
        return getattr(sys.__stdout__, name)

sys.stdout = ExpFloatFileObject()  

and usage:

>>> 14000    
1.400000e+04  
>>> "text"
'text'

#5


When using IPython/Jupyter-console, the "magic" command %precision %e will change the display of raw floats in exponential notation. https://ipython.readthedocs.io/en/stable/interactive/magics.html#magic-precision

使用IPython / Jupyter-console时,“magic”命令%precision%e将以指数表示法更改原始浮点数的显示。 https://ipython.readthedocs.io/en/stable/interactive/magics.html#magic-precision

For more formatting control, a formatter can be registered:

要进行更多格式控制,可以注册格式化程序:

excited_floats = lambda val: "{:e}!!!".format(val)
console_formatter = get_ipython().display_formatter.formatters['text/plain']
console_formatter.for_type(float, lambda val, p, c: p.text(excited_floats(val)))

https://ipython.readthedocs.io/en/stable/api/generated/IPython.core.formatters.html#IPython.core.formatters.PlainTextFormatter

#1


Create a Python script called whatever you want (say mystartup.py) and then set an environment variable PYTHONSTARTUP to the path of this script. Python will then load this script on startup of an interactive session (but not when running scripts). In this script, define a function similar to this:

创建一个名为您想要的Python脚本(比如mystartup.py),然后将环境变量PYTHONSTARTUP设置为此脚本的路径。然后,Python将在启动交互式会话时加载此脚本(但在运行脚本时不会)。在此脚本中,定义一个类似于此的函数:

def _(v):
    if type(v) == type(0.0):
        print "%e" % v
    else:
        print v

Then, in an interactive session:

然后,在交互式会话中:

C:\temp>set PYTHONSTARTUP=mystartup.py

C:\temp>python
ActivePython 2.5.2.2 (ActiveState Software Inc.) based on
Python 2.5.2 (r252:60911, Mar 27 2008, 17:57:18) [MSC v.1310 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> _(1e12)
1.000000e+012
>>> _(14)
14
>>> _(14.0)
1.400000e+001
>>>

Of course, you can define the function to be called whaetver you want and to work exactly however you want.

当然,您可以将要调用的函数定义为所需的函数,并根据需要正确工作。

Even better than this would be to use IPython. It's great, and you can set the number formatting how you want by using result_display.when_type(some_type)(my_print_func) (see the IPython site or search for more details on how to use this).

比这更好的是使用IPython。这很棒,您可以使用result_display.when_type(some_type)(my_print_func)设置数字格式(请参阅IPython网站或搜索有关如何使用此内容的更多详细信息)。

#2


Hm... It's not a 100% solution, but this have come to my mind...

嗯...这不是100%的解决方案,但我想到了......

How about defining a subclass of float which would have an overridden __str__ method (to print with the exp notation). And then you would have to wrap all the expressions with object construction of this class). It would be a bit shorter than Dave's solution, you would define the class once and then write something like:

如何定义一个浮点的子类,它将具有重写的__str__方法(使用exp表示法打印)。然后你必须用这个类的对象构造包装所有表达式)。它会比Dave的解决方案稍短,你可以定义一次类,然后写一些类似的东西:

>>> F(1.e12)
1.0e+12
>>> F(3.)
3.0e+0
>>> F(1.+2.+3.+4.)
1.0e+1
...

#3


As you know you can use the % operator or str.format to format strings:

如您所知,您可以使用%operator或str.format格式化字符串:

For example:

>>> "%e" % 1.e12
'1.000000e+12'

I was wondering if you could monkey patch the built-in float class to change the formatting but it seems that Python won't let you:

我想知道你是否可以修补内置的float类来改变格式,但似乎Python不会让你:

>>> 1.e12.__class__.__repr__ = lambda x: "%e" % x
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can't set attributes of built-in/extension type 'float'

So the only other thing I can think of is to write your own file-like object which captures output, reformats it and sends it to the standard output. You'd then redirect standard output of the interpreter to this object:

因此,我能想到的唯一另一件事就是编写自己的类文件对象,捕获输出,重新格式化并将其发送到标准输出。然后,您将解释器的标准输出重定向到此对象:

sys.stdout = my_formatting_object

#4


Building on Dave Webb's hint above. You can of course set the precision if you like ("%.3e") and perhaps override writelines if needed.

基于Dave Webb的上述提示。您当然可以根据需要设置精度(“%。3e”),如果需要也可以覆盖writelines。

import os
import sys

class ExpFloatFileObject:
    def write(self, s):
        try:
            s = "%e"%float(s)
        except ValueError:
            pass
        sys.__stdout__.write(s)

    def __getattr__(self, name):
        return getattr(sys.__stdout__, name)

sys.stdout = ExpFloatFileObject()  

and usage:

>>> 14000    
1.400000e+04  
>>> "text"
'text'

#5


When using IPython/Jupyter-console, the "magic" command %precision %e will change the display of raw floats in exponential notation. https://ipython.readthedocs.io/en/stable/interactive/magics.html#magic-precision

使用IPython / Jupyter-console时,“magic”命令%precision%e将以指数表示法更改原始浮点数的显示。 https://ipython.readthedocs.io/en/stable/interactive/magics.html#magic-precision

For more formatting control, a formatter can be registered:

要进行更多格式控制,可以注册格式化程序:

excited_floats = lambda val: "{:e}!!!".format(val)
console_formatter = get_ipython().display_formatter.formatters['text/plain']
console_formatter.for_type(float, lambda val, p, c: p.text(excited_floats(val)))

https://ipython.readthedocs.io/en/stable/api/generated/IPython.core.formatters.html#IPython.core.formatters.PlainTextFormatter