gpt4 book ai didi

python - 如何使 f"..."字符串格式使用逗号而不是点作为小数点分隔符?

转载 作者:行者123 更新时间:2023-12-03 07:58:45 24 4
gpt4 key购买 nike

我尝试过:

import locale
print(locale.locale_alias)
locale.setlocale(locale.LC_ALL, '')
locale.setlocale(locale.LC_NUMERIC, "french")
print(f"{3.14:.2f}")

但是输出是3.14,而我想要3,14

如何使用 f"..."字符串格式来执行此操作?

注意:我不想使用 .replace(".", ",")

注意:我正在寻找 Windows 解决方案,以及来自 How to format a float with a comma as decimal separator in an f-string? 的解决方案不起作用(因此它在 Windows 上不是重复的):

locale.setlocale(locale.LC_ALL, 'nl_NL')
# or
locale.setlocale(locale.LC_ALL, 'fr_FR')

locale.Error: unsupported locale setting

最佳答案

我在重复标记的页面上查找了答案,并找到了有效的答案:

print(f"{3.14:.2f}") 更改为 print(f"{3.14:.3n}") ,您将得到结果: 3,14

参见https://docs.python.org/3/library/string.html#format-specification-mini-language :

'n' Number. This is the same as 'g', except that it uses the current locale setting to insert the appropriate number separator characters.

'g' 的描述如下:

g General format. For a given precision p >= 1, this rounds the number to p significant digits and then formats the result in either fixed-point format or in scientific notation, depending on its magnitude. A precision of 0 is treated as equivalent to a precision of 1....Truncated...

'f' 描述为:

'f' Fixed-point notation. For a given precision p, formats the number as a decimal number with exactly p digits following the decimal point.

关于python - 如何使 f"..."字符串格式使用逗号而不是点作为小数点分隔符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75068739/

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