【发布时间】:2011-04-23 23:50:39
【问题描述】:
可能重复:
How to print number with commas as thousands separators?
例如:
>> print numberFormat(1234)
>> 1,234
或者 Python 中有没有内置函数可以做到这一点?
【问题讨论】:
可能重复:
How to print number with commas as thousands separators?
例如:
>> print numberFormat(1234)
>> 1,234
或者 Python 中有没有内置函数可以做到这一点?
【问题讨论】:
到目前为止,还没有人提到新的',' 选项,它是在 2.7 版中添加到 Format Specification Mini-Language 的——请参阅 What's New in Python 2.7 document 中的 PEP 378: Format Specifier for Thousands Separator。它很容易使用,因为您不必乱用locale(但因此受到国际化限制,请参阅original PEP 378)。它适用于浮点数、整数和小数——以及迷你语言规范中提供的所有其他格式功能。
示例用法:
print format(1234, ",d") # -> 1,234
print "{:,d}".format(1234) # -> 1,234
print(f'{1234:,d}') # -> 1,234 (Python 3.6+)
注意:虽然这个新功能确实很方便,但实际上并没有像其他几个人所建议的那样,使用locale 模块要困难得多。其优点是,在输出数字、日期和时间等内容时,可以使数字输出自动遵循各个国家/地区使用的适当的千位(和其他)分隔符约定。无需学习大量语言和国家/地区代码,即可将计算机中的默认设置生效也很容易。您需要做的就是:
import locale
locale.setlocale(locale.LC_ALL, '') # empty string for platform's default settings
完成此操作后,您可以使用通用的'n' 类型代码来输出数字(整数和浮点数)。在我所在的地方,逗号用作千位分隔符,所以在设置了如上所示的语言环境后,会发生这种情况:
print format(1234, "n") # -> 1,234
print "{:n}".format(1234) # -> 1,234
世界其他大部分地区为此使用句点而不是逗号,因此在许多位置设置默认区域设置(或在setlocale() 调用中明确指定此类区域的代码)会产生以下结果:
print format(1234, "n") # -> 1.234
print "{:n}".format(1234) # -> 1.234
基于'd' 或',d' 格式化类型说明符的输出不受setlocale() 的使用(或不使用)影响。但是,如果您改为使用 locale.format() 或 locale.format_string() 函数,则 'd' 说明符会受到影响。
【讨论】:
format(1234, u"n")。你会得到新手最喜欢的例外:UnicodeDecodeError: 'ascii' codec can't decode byte 0xa0 ...
locale 的注释之前,大多数人都对这个答案进行了投票 - 为了大家的启发,是 i> 目前正确的为什么要以特定于语言环境的方式进行操作以处理 Unicode?谢谢。
format(1234, "n").decode(locale.getpreferredencoding()) :-(
locale 不适用于 Unicode 字符串。我的错(即使我从未声称它确实如此)。如果语言环境设置为法语,format(1234, "n") 会生成1 234,不会引发异常。 给您的问题:您为什么不反对或至少评论此处建议使用locale 作为主要答案的其他答案?
'{:,.2f}'.format(mydollars) 格式为美元和美分。
从webpyutils.py剥离:
def commify(n):
"""
Add commas to an integer `n`.
>>> commify(1)
'1'
>>> commify(123)
'123'
>>> commify(1234)
'1,234'
>>> commify(1234567890)
'1,234,567,890'
>>> commify(123.0)
'123.0'
>>> commify(1234.5)
'1,234.5'
>>> commify(1234.56789)
'1,234.56789'
>>> commify('%.2f' % 1234.5)
'1,234.50'
>>> commify(None)
>>>
"""
if n is None: return None
n = str(n)
if '.' in n:
dollars, cents = n.split('.')
else:
dollars, cents = n, None
r = []
for i, c in enumerate(str(dollars)[::-1]):
if i and (not (i % 3)):
r.insert(0, ',')
r.insert(0, c)
out = ''.join(r)
if cents:
out += '.' + cents
return out
还有其他解决方案here。
【讨论】:
enumerate() 迭代器被替换为等价的东西,则一直回到 2.0 版。
str(dollars)[::-1] 可以替换为更易读的reversed(str(dollars))。
str(dollars)之前,美元不是已经是一个字符串了吗?
在整数上使用locale.format(),但要注意您环境中的当前语言环境。某些环境可能没有此设置或设置为不会给您带来 commafied 结果的东西。
这是我必须编写的一些代码来处理这个确切的问题。它会根据您的平台自动为您设置语言环境:
try:
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') #use locale.format for commafication
except locale.Error:
locale.setlocale(locale.LC_ALL, '') #set to default locale (works on windows)
score = locale.format('%d', player['score'], True)
【讨论】:
不要忘记首先适当地设置语言环境。
【讨论】:
True 值,例如locale.format(u'%d', 1234, True)。显然locale 在处理 Unicode 方面并非完全无能为力(正如 @John Machin 在另一个答案中的 cmets 似乎暗示的那样)。