郵件收錄在: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 <[email protected]>
reply-to [email protected]
to python-cn`CPyUG`華蟒用戶組 <[email protected]>
date Tue, Jan 13, 2009 at 16:53
subject [CPyUG:76807] Re: python怎麼輸出1,233,232這種形式?
http://www.jaharmi.com/2008/05/26/format_numbers_with_the_python_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 <[email protected]>
reply-to [email protected]
to [email protected]
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";