Python格式化千分位数字

Python 2.7及以上版本直接使用format设置千分位分隔符

1
2
3
4
5
Python 2.7.14 (v2.7.14:84471935ed, Sep 16 2017, 20:25:58) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> format(1234567890, ',')
'1,234,567,890'
>>>

正则实现

1
2
3
4
5
6
7
8
import re
def number_format(s):
s = str(s)
while True:
(s, count) = re.subn(r"(\d)(\d{3})((:?,\d\d\d)*)$", r"\1,\2\3", s)
if count == 0 : break
return s
print number_format(1234567890)

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2020 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :