1、最简单的内置format函数:
>>> format(1234567890,',') '1,234,567,890'
2、正则表达式:
import re def formatNum(num): num=str(num) pattern=r'(d+)(d{3})((,d{3})*)' while True: num,count=re.subn(pattern,r'1,23',num) if count==0: break return num if __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)