2012-04-09 231 views
2

可能重复:
how to print number with commas as thousands separators in Python 2.x千位分隔符在Python

有谁知道一个更简单的方法,使数字有数千分离比这

def addComma(num): 
    (num, post) = str(num).split('.') 
    num = list(num) 
    num.reverse() 

    count = 0 
    list1 = [] 

    for i in num: 
     count += 1 
     if count % 3 == 0: 
      list1.append(i) 
      list1.append(',') 
     else: 
      list1.append(i) 

    list1.reverse() 

    return ''.join(list1).strip(',') + '.' + post 

它的工作原理,但它似乎真的很脆弱......

+0

这已被问及在这里回答几次:[1](http://stackoverflow.com/questions/1823058/how-to-print-number-with-commas-as-thousands-separators-in -python-2-x),[2](http://stackoverflow.com/questions/3909457/whats-the-easiest-way-to-add-commas-to-an-integer-in-python),[ 3](http://stackoverflow.com/questions/5180365/python-add-comma-into-number-string) – 2012-04-09 20:19:54

回答