Is it possible to mix elegantly f-strings with locale.format in Python 3.6

Viewed 799

Python 3.6 (a.k.a. PEP 498) introduces formatted strings that I love. In certain cases we have to output the large numbers that is difficult for users to read. I used locale grouping as in an example below. I wonder if there is a better way to format large numbers inside of formatted strings?

import locale
locale.setlocale(locale.LC_ALL, 'en_US')
count = 80984932412380
s = f'Total count is:{locale.format("%d", count, grouping = True)}'
>>> s
'Total count is:80,984,932,412,380'

Many thanks in advance for help!

3 Answers

One can use the libary babel as a thread-safe alternative for locale:

from babel.numbers import format_decimal
count = 80984932412380

s = f'Total count is: {format_decimal(count, locale="en_US")}'
>>> s
'Total count is: 80,984,932,412,380'

If you prefer shorter f-strings, you can define a custom function:

def number(x):
    return format_decimal(x, locale="en_US")

f'Total count is: {number(count)}'
>>> s
'Total count is: 80,984,932,412,380'

The locale module is a bit clumsy, but a function can wrap it nicely:

import locale

locale.setlocale(locale.LC_ALL, '')

def format_num(value, spec='%d'):
    return locale.format_string(spec, value, grouping=True)


count = 80984932412380

>>> f'Total count is: {format_num(count)}.'
'Total count is: 80,984,932,412,380.'
Related