千分位输出 1,233,232格式

千分位输出 1,233,232格式

摘抄自邮件列表,我的方法比较土,小数点也没有加进去,locale未尽测试。
邮件收录在:http://wiki.woodpecker.org.cn/moin/MiscItems/2009-01-13

最新方法:
>>> while True:
...     (s,count) = re.subn(r"(\d)(\d{3})((:?,\d\d\d)*)$",r"\1,\2\3",s)
...     if count == 0 : break

locale
国外同志们有遇到同样的问题。看这里:
http://bytes.com/groups/python/454763-number-format-function
其中有个回帖是这样的。
This is a little faster:
def number_format(num, places=0):

    """Format a number according to locality and given places"""
    locale.setlocale(locale.LC_ALL, "")
    return locale.format("%.*f", (places, num), True)

    I tested this ok with my test

再一例
eric <pony.ch@gmail.com>
reply-to        python-cn@googlegroups.com
to      python-cn`CPyUG`华蟒用户组 <python-cn@googlegroups.com>
date    Tue, Jan 13, 2009 at 16:53
subject [CPyUG:76807] Re: python怎么输出1,233,232这种形式?

http://www.jaharmi.com/2008/05/2 ... ython_locale_module

>>> import locale
>>> a = {'size': 123456789, 'unit': 'bytes'}
>>> print(locale.format("%(size).2f", a, 1))
123456789.00
>>> locale.setlocale(locale.LC_ALL, '') # Set the locale for your system
'en_US.UTF-8'
>>> print(locale.format("%(size).2f", a, 1))
123,456,789.00

DIY
smallfish <smallfish@live.cn>
reply-to        python-cn@googlegroups.com
to      python-cn@googlegroups.com
date    Tue, Jan 13, 2009 at 16:53
subject [CPyUG:76806] Re: python怎么输出1,233,232这种形式?

我试了一个土方法:

>>> s = "1234567890"
>>> s = s[::-1]
>>> a = [s[i:i+3] for i in range(0,len(s),3)]
>>> print (",".join(a))[::-1]

--------------------------------------------------------------------------------

其实用perl实现感觉更简单了些:
$size = "1234567890";
1 while $size =~ s/(\d)(\d{3})((:?,\d\d\d)*)$/$1,$2$3/;
print $size, "\n";
perl那个表达式看得我头晕~~
(s,count) = re.subn(r"(\d)(\d{3})((,\d\d\d)*)$",r"\1,\2\3",s)  这个表达式好像只对 这个数字起效果哦