gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 02:44:38 24 4
gpt4 key购买 nike

Python 3.6(又名 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'

非常感谢您的帮助!

最佳答案

可以使用库 babel作为语言环境的线程安全替代方案:

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 字符串,您可以定义一个自定义函数:

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'

关于python - 是否可以在 Python 3.6 中优雅地混合 f-strings 和 locale.format,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45491862/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com