Python 将逗号添加到整数的最简单方法是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3909457/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What's the easiest way to add commas to an integer?
提问by ensnare
Possible Duplicate:
How to print number with commas as thousands separators?
可能的重复:
如何用逗号作为千位分隔符打印数字?
For example:
例如:
>> print numberFormat(1234)
>> 1,234
Or is there a built-in function in Python that does this?
或者 Python 中是否有一个内置函数可以做到这一点?
采纳答案by martineau
No one so far has mentioned the new ','option which was added in version 2.7 to the Format Specification Mini-Language-- see PEP 378: Format Specifier for Thousands Separatorin the What's New in Python 2.7 document. It's easy to use because you don't have to mess around with locale(but is limited for internationalization due to that, see the original PEP 378). It works with floats, ints, and decimals — and all the other formatting features provided for in the mini-language spec.
到目前为止,没有人提到','在 2.7 版中添加到格式规范迷你语言的新选项——请参阅PEP 378:Python 2.7 新特性文档中的千位分隔符的格式说明符。它易于使用,因为您不必弄乱locale(但由于国际化而受到限制,请参阅原始 PEP 378)。它适用于浮点数、整数和小数——以及迷你语言规范中提供的所有其他格式功能。
Sample usage:
示例用法:
print format(1234, ",d") # -> 1,234
print "{:,d}".format(1234) # -> 1,234
Note:While this new feature is definitely handy, it's actually notall that much harder to use the localemodule, as several others have suggested. The advantage is that then numeric output can be made to automatically follow the proper thousands (and other) separator conventions used in various countries when outputting things like numbers, dates, and times. It's also very easy to put the default settings from your computer into effect without learning a bunch of language and country codes. All you need to do is:
注:虽然这个新功能是,绝对好用,它实际上并不是所有的更难使用的locale模块,其他几个建议。优点是,在输出数字、日期和时间等内容时,可以使数字输出自动遵循不同国家/地区使用的正确千位(和其他)分隔符约定。无需学习大量语言和国家/地区代码,即可轻松地将计算机的默认设置生效。您需要做的就是:
import locale
locale.setlocale(locale.LC_ALL, '') # empty string for platform's default settings
After doing that you can just use the generic 'n'type code for outputting numbers (both integer and float). Where I am, commas are used as the thousand separator, so after setting the locale as shown above, this is what would happen:
这样做之后,您可以只使用通用'n'类型代码来输出数字(整数和浮点数)。在我所在的位置,逗号用作千位分隔符,因此在设置如上所示的语言环境后,会发生以下情况:
print format(1234, "n") # -> 1,234
print "{:n}".format(1234) # -> 1,234
Much of the rest of the world uses periods instead of commas for this purpose, so setting the default locale in many locations (or explicitly specifying the code for such a region in a setlocale()call) produces the following:
世界其他地方的大部分地区为此目的使用句点而不是逗号,因此在许多位置设置默认语言环境(或在setlocale()调用中明确指定此类区域的代码)会产生以下结果:
print format(1234, "n") # -> 1.234
print "{:n}".format(1234) # -> 1.234
Output based on the 'd'or ',d'formatting type specifier is unaffected by the use (or non-use) of setlocale(). However the 'd'specifier isaffected if you instead use the locale.format()or locale.format_string()functions.
基于'd'或',d'格式类型说明符的输出不受使用(或不使用) 的影响setlocale()。但是,如果您改为使用or函数,'d'说明符会受到影响。locale.format()locale.format_string()
回答by Ignacio Vazquez-Abrams
回答by systempuntoout
Stripped from webpyutils.py:
从webpy 中剥离utils.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
There are other solutions here.
还有其他的解决方案在这里。
回答by Aphex
Use locale.format()on the integer, but beware of the current locale on your environment. Some environments may not have this set or set to something that won't give you a commafied result.
locale.format()在整数上使用,但要注意您环境中的当前语言环境。某些环境可能没有此设置或设置为不会给您逗号结果的内容。
Here's some code I had to write to deal with this exact issue. It'll automatically set the locale for you depending on your platform:
这是我必须编写的一些代码来处理这个确切的问题。它会根据您的平台自动为您设置语言环境:
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)

