Python對數字的千分位處理方式

佚名發表於2022-05-17

對數字的千分位處理

方法1

>>> "{:,}".format(56381779049)
'56,381,779,049'
>>> "{:,}".format(56381779049.1)
'56,381,779,049.1'
>>>

方法2

>>> import re
>>> subject = '1234567'
>>> result = re.sub(r"(?<=\d)(?=(?:\d\d\d)+$)", ",", subject)
>>> result
'1,234,567'

方法3

>>> import re
>>> subject = '1234567'
>>> result = re.sub(r"(\d)(?=(\d\d\d)+(?!\d))", r"\1,", subject)
>>> result
'1,234,567'

格式化千分位數字

2.7版本以上直接用format設定千分位分隔符

python 2.7 (r27:82500, nov 23 2010, 18:07:12)
[gcc 4.1.2 20070115 (prerelease) (suse linux)] on linux2
type "help", "copyright", "credits" or "license" for more information.
>>> format(1234567890,',')
'1,234,567,890'
>>> 

正則實現

import re
def strconv(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 strconv(12345)

以上為個人經驗,希望能給大家一個參考,

相關文章