首页 > 代码库 > Python数字加千分符

Python数字加千分符

1、最简单的内置format函数:

>>> format(1234567890,‘,‘)‘1,234,567,890‘

2、正则表达式:

import redef formatNum(num):    num=str(num)    pattern=r‘(\d+)(\d{3})((,\d{3})*)‘    while True:        num,count=re.subn(pattern,r‘\1,\2\3‘,num)        if count==0:            break    return numif __name__==‘__main__‘:    print formatNum(1234455)

3、最笨的倒置后遍历过三位加逗号:

def formatNum(num):    num=str(num)    result=‘‘    count=0    for i in num[::-1]:        count+=1        result+=i        if count%3==0:            result+=‘,‘      return result[::-1].strip(‘,‘)if __name__==‘__main__‘:    print formatNum(123445)

  

Python数字加千分符