[issue43624] Add underscore as a decimal separator for string formatting

STINNER Victor report at bugs.python.org
Fri Mar 26 08:09:26 EDT 2021


STINNER Victor <vstinner at python.org> added the comment:

How backward incompatible and annoying would it be to modify the behavior of the existing "_f" format?

Do you see use cases which only want to group digits in the integer part but not the fractional part?

According to https://discuss.python.org/t/add-underscore-as-a-thousandths-separator-for-string-formatting/7407 discussion, grouping digits was first designed for integers, and the fractional part of floats was simply ignored/forgotten. I mean, it doesn't sound like a deliberate choice to not group digits in the fractional part.

The advantage of changing "_f" format is to keep backward compatibility: Python 3.9 and older would not group digits in the fractional part, but at least they don't fail with an error. If you write code with "_._f" format, you need a fallback code path for Python 3.9 and older:

if sys.version_info >= (3, 10):
   text = f"my {...} very {...} long {...} and {...} complex {...} format string: x={x:_._f}"
else:
   text = f"my {...} very {...} long {...} and {...} complex {...} format string: x={x:_f}"

Or:

text = f"my {...} very {...} long {...} and {...} complex {...} format string:" + (f"x={x:_f}" if sys.version_info >= (3, 10) else "x={x:_f}")

Or many other variants.

The main drawback is the risk to break tests relying on the exact output.

About the separator character and the number of digits per group, IMO there is no standard working in all countries and all languages. But since we have a strict rule of 3 digits with "_" separator, I am fine with doing the same for the fractional part. It's an "arbitrary" choice, but at least, it's consistent.

People wanting a different format per locale/language should write their own function. Once enough people will agree on such API, we can consider to add it to the stdlib. But for now, IMO 3 digits with "_" is good enough.

By the way, I agree that it's hard to read numbers with many digits in the decimal part ;-)

>>> f"{1/7:_.30f}"
'0.142857142857142849212692681249'

>>> f"{10**10+1/7:_.10f}"
'10_000_000_000.1428565979'

----------

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue43624>
_______________________________________


More information about the Python-bugs-list mailing list