Python 字符串格式化

1 投票
4 回答
1967 浏览
提问于 2025-04-16 09:24

我想弄明白在字符串格式化中,n这个选项值到底有什么作用,特别是在type标志下。

PEP 3101中提到(在可用整数类型的部分):

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

我试了以下代码:

print "This is a large number with formatting applied: {0:n}".format(1384309238430)

我得到了这个输出:

This is a large number with formatting applied: 1384309238430

也就是说,没有出现任何数字分隔符。请问我怎么查找我的地区设置?我该如何获取数字分隔符(我在想,数字分隔符可能指的是像千位分隔符的逗号之类的东西)。

4 个回答

1

你需要调用 setlocale 这个函数,可能在 locale 参数里传一个空字符串。

3

这完全取决于地区设置:

>>> print "{0:n}".format(134.3)
134.3
>>> import locale
>>> locale.getlocale()
(None, None)
>>> locale.setlocale(locale.LC_ALL, 'de_DE')
'de_DE'
>>> print "{0:n}".format(134.3)
134,3
>>> print "{0:n}".format(13423.3)
13423,3
>>> locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
'en_US.UTF-8'
>>> print "{0:n}".format(13423.3)
13,423.3
>>> 
11
import locale
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
print('{0:n}'.format(1234))

产生

1,234

你可以用 locale.getlocale() 来查看你当前的地区设置:

In [31]: locale.getlocale()
Out[31]: ('en_US', 'UTF8')

而用 locale.getdefaultlocale() 可以查看默认的地区设置。

在 *nix 系统上,你可以通过命令 locale -a 来获取你机器上已知的地区设置列表。

撰写回答