是否可以在 Python 3.6 中优雅地混合 f-strings 与 locale.format

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

Python 3.6 (a.k.a. PEP 498) 引入了我喜欢的格式化字符串。在某些情况下,我们必须输出用户难以阅读的大数字。我在下面的示例中使用了语言环境分组。我想知道是否有更好的方法来格式化格式化字符串中的大数字?

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'

非常感谢您的帮助!

这是一个偏好问题。代码确实和用的比较多的字符串格式化方法没什么区别。这也可以让我更具可读性。

import locale
locale.setlocale(locale.LC_ALL, 'en_US')
count = 80984932412380
s = 'Total count is: {}'.format(locale.format("%d",count))

可以使用库 babel 作为语言环境的 thread-safe 替代:

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'

如果你喜欢更短的f-strings,你可以定义一个自定义函数:

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'

语言环境模块有点笨拙,但是一个函数可以很好地包装它:

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