I am using ipython
5.8.0
on Debian 10
.
This is how output looks like:
In [1]: 50*50
Out[1]: 2500
Is it possible to configure ipython
to print all numbers with thousands separators? ie:
In [1]: 50*50
Out[1]: 2'500
In [2]: 5000*5000
Out[2]: 25'000'000
And perhaps, is it possible to make ipython
also understand thousands separators on input?
In [1]: 5'000*5'000
Out[1]: 25'000'000
UPDATE
The accepted answer from @Chayim Friedman
works for integers, but does not work for float:
In [1]: 500.1*500
Out[1]: 250050.0
Also, when it works, it uses ,
as the character for thousand separator:
In [1]: 500*500
Out[1]: 250,000
Can I use '
instead?
4
Answers
After update: you can subclass int:
I don’t believe you can achieve all that you are looking for without rewriting the iPython interpreter, which means changing the Python language specification, to be able to input numbers with embedded
'
characters and have them ignored. But you can achieve some of it. Subclassing theint
class is a good start. But you should also overload the various operators you plan on using. For example:Prints:
Update
It seems that for Python 3.7 you need to override the
__str__
method rather than the__repr__
method. This works for Python 3.8 and should work for later releases as well.Update 2
Prints:
An alternative if you have package
Babel
from thePyPi
repository:Prints:
Or if you prefer to custom-tailor a locale just for this purpose and leave the standard
en_US
locale unmodified. This also shows how you can parse input values:Prints:
Based on PEP-0378, you can use the following code:
It will produce:
Using
'
as thousands separator in input is quite problematic because Python uses'
to delimit strings, but you can use_
(PEP 515, Underscores in Numeric Literals):Regarding output, this is slightly harder, but can be done using IPython extensions.
Put the following Python code in a new file at ~/.ipython/extensions/thousands_separator.py:
This code tells IPython to replace the default
int
formatter with one that prints thousand separators when this extension is loaded, and restore the original when it is unloaded.Edit: If you want a different separator, for instance
'
, replace thef'{number:,}'
withf'{number:,}'.replace(',', "'")
.You can load the extension using the magic command
%load_ext thousands_separator
and unload it using%unload_ext thousands_separator
, but if you want it always, you can place it in the default profile.Run the following code in the terminal:
It will report that a file ~/.ipython/profile_default/ipython_config.py was created. Enter it, and search for the following string:
Replace it with the following:
This tells IPython to load this extension by default.
Done!
Edit: I saw that you want to a) use
'
as separator, and b) do the same for floats:Using different separator is quite easy: just
str.replace()
:Doing the same for floats is also easy: just setup
print_int
so it prints floats to. I also suggest to change the name toprint_number
.Final code: