如何在f字符串中使用逗号作为小数点分隔符格式化浮点数?

19

对于Python中的一些机器控制,我将结果写入文本文件,以便其他人可以将其复制到Excel中(在这种情况下,这是最方便的方法)。然而,在荷兰,Excel使用逗号作为小数分隔符,因此我希望在文本文件中将“位置”结果显示为123,456。但是,当我使用如下的f-string方法时:

    resultfile.write(f"Position\t{position:.5}")

这显然会导致使用点作为小数分隔符。
我该如何在不迭代整个文件并替换点号的情况下将其更改为逗号?

2
一个fstring只是一个字符串,所以 f"Position\t{position:.5}".replace('.', ',') 应该可以正常工作,对吧? - Arne
2
另外:https://dev59.com/aWw15IYBdhLWcg3wZ68Y#6633912 这个答案谈到了不同的问题(在每三个小数位处用逗号分隔打印数字),但语言环境设置也可能影响您的格式。 - Arne
5个回答

14

如果你想在f-string中使用逗号格式化浮点数,可以将浮点数转换为字符串后再使用replace函数:

position = 123.456
f"Position\t{str(position).replace('.',',')}"

第二个选择是使用Python标准库模块locale (但它不是线程安全的):

import locale
locale.setlocale(locale.LC_ALL, 'nl_NL')
f"Position\t{locale.format('%.3f', position)}"

第三种选择是使用库babel(在库例程的情况下首选):

from babel.numbers import format_decimal
f"Position\t{format_decimal(position, locale='nl_NL')}"

对于给定的示例,这三个选项返回相同的结果:

'Position\t123,456'

3
如果您希望避免依赖项,下面的简单函数可能适合您的需求:
def comma_num(n,f=''):
    return ('{'+f+'}').format(n).replace('.',',')

n = 1.23

f'Whatever {comma_num(n)}'
'Whatever {}'.format(comma_num(n))
>>>'Whatever 1,23'

f'Whatever {comma_num(n,":6.4f")}'
'Whatever {}'.format(comma_num(n,':6.4f'))
>>>'Whatever 1,2300'

3

正如 @michel-de-ruiter 提到 的那样,f 格式不能与区域设置一起使用。另一方面,您无法使用 n 格式设置精度。例如,如果您想要小数点后4位:

import locale
locale.setlocale(locale.LC_ALL, 'nl_NL')

position = 123.45678999
print(f'{position:.4n}')  # output: 123,4 (not quite what we wanted!)

然而,在格式化之前,您可以使用所需的精度四舍五入数字:
print(f'{round(position, 4):n}')  # output: 123,4567 (that's it!)

2
如果g格式已经满足您的需求,可以使用n代替:
resultfile.write(f"Position\t{position:.7n}")

虽然n可以使用当前区域设置,但无法替代dg。不幸的是,对于f格式没有这样的选项...


-3
一个更简单的解决方案可能是:

f"Position\t{position:,.5f}"

9
这将把“千分位分隔符”更改为“,”,但问题询问的是“小数点分隔符”。它根本没有回答问题。 - marcelm
@seaver 这并没有回答问题。它只是引入了千位分隔符(,),却没有改变小数分隔符(仍然是.)。 - Michel de Ruiter

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接