Search code examples
pythonipython

How do I control number formatting in the python interpreter?


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?

For example, I want:

>>> 1.e12
1.0e+12

not:

>>> 1.e12
1000000000000.0

Solution

  • 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:

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