题
我想打印的整数 蟒蛇2.6.1 用逗号分开作为千分离器。例如,我想告诉的数量 1234567
作为 1,234,567
.我怎么会去做这个?我已经看到许多例子,在谷歌,但我要寻找最简单实用的方法。
它不需要区域特定的决定之间的时间和逗号。我会更喜欢一些简单的合理可能的。
解决方案
区域设置未察觉
'{:,}'.format(value) # For Python ≥2.7
f'{value:,}' # For Python ≥3.7
区域设置感知
import locale
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') # Customize
'{:n}'.format(value) # For Python ≥2.7
f'{value:n}' # For Python ≥3.7
参考
在
','
选项信号的千分离器中使用逗号。对于一个区域设置感知分离器,使用'n'
整数呈现类型,而不是
其他提示
我得到这个工作:
>>> import locale
>>> locale.setlocale(locale.LC_ALL, 'en_US')
'en_US'
>>> locale.format("%d", 1255000, grouping=True)
'1,255,000'
当然,你不这样做的需要的国际化支持,但它的清晰,简洁,并采用了内置库。
P.S。这“%d”,是平时的风格%格式。你只能有一个格式,但它可以是任何你在外地宽度和精度设置方面需要。
P.P.S。如果你不能得到locale
工作,我建议马克的回答修改后的版本:
def intWithCommas(x):
if type(x) not in [type(0), type(0L)]:
raise TypeError("Parameter must be an integer.")
if x < 0:
return '-' + intWithCommas(-x)
result = ''
while x >= 1000:
x, r = divmod(x, 1000)
result = ",%03d%s" % (r, result)
return "%d%s" % (x, result)
递归为否定的情况下是有用的,但每一个逗号递归似乎有点过度我。
有关的低效率和不可读性很难击败:
>>> import itertools
>>> s = '-1234567'
>>> ','.join(["%s%s%s" % (x[0], x[1] or '', x[2] or '') for x in itertools.izip_longest(s[::-1][::3], s[::-1][1::3], s[::-1][2::3])])[::-1].replace('-,','-')
下面是语言环境去除不相关部分并清除它之后分组码一点:
(以下只对整数)
def group(number):
s = '%d' % number
groups = []
while s and s[-1].isdigit():
groups.append(s[-3:])
s = s[:-3]
return s + ','.join(reversed(groups))
>>> group(-23432432434.34)
'-23,432,432,434'
有已经在这里一些很好的答案。我只想补充这个以供将来参考。在Python 2.7版存在将是千位分隔符的格式说明符。根据 python文档一>它是这样工作的
>>> '{:20,.2f}'.format(f)
'18,446,744,073,709,551,616.00'
在python3.1,你可以做同样的事情是这样的:
>>> format(1234567, ',d')
'1,234,567'
我很惊讶,没有人提到,您可以用Python F-字符串做3.6那么容易,因为这样的:
>>> num = 10000000
>>> print(f"{num:,d}")
10,000,000
...其中冒号之后的部分是格式说明。逗号是所需的分隔符,所以f"{num:_d}"
使用下划线,而不是一个逗号。
这相当于使用format(num, ",d")
为旧版本的Python 3的
下面是一个单行的正则表达式替换:
re.sub("(\d)(?=(\d{3})+(?!\d))", r"\1,", "%d" % val)
仅适用于inegral输出:
import re
val = 1234567890
re.sub("(\d)(?=(\d{3})+(?!\d))", r"\1,", "%d" % val)
# Returns: '1,234,567,890'
val = 1234567890.1234567890
# Returns: '1,234,567,890'
或用于与小于4位浮筒,该格式说明更改为%.3f
:
re.sub("(\d)(?=(\d{3})+(?!\d))", r"\1,", "%.3f" % val)
# Returns: '1,234,567,890.123'
<强> NB:强>不超过三个十进制数字正确地工作,因为它会尝试组的小数部分:
re.sub("(\d)(?=(\d{3})+(?!\d))", r"\1,", "%.5f" % val)
# Returns: '1,234,567,890.12,346'
工作原理
让我们来分析一下:
re.sub(pattern, repl, string)
pattern = \
"(\d) # Find one digit...
(?= # that is followed by...
(\d{3})+ # one or more groups of three digits...
(?!\d) # which are not followed by any more digits.
)",
repl = \
r"\1,", # Replace that one digit by itself, followed by a comma,
# and continue looking for more matches later in the string.
# (re.sub() replaces all matches it finds in the input)
string = \
"%d" % val # Format the string as a decimal to begin with
这是我的花车做。虽然,说实话,我不知道它适用于哪个版本 - 我使用2.7:
my_number = 4385893.382939491
my_string = '{:0,.2f}'.format(my_number)
返回:4,385,893.38
更新:我最近有一个问题,这种格式(不能告诉你确切的原因),但能够通过删除解决它0
:的
my_string = '{:,.2f}'.format(my_number)
您也可以使用'{:n}'.format( value )
一个本地化表示。我认为这是地区溶液simpliest方式。
有关的详细信息,在的Python DOC搜索thousands
一>
有关货币,可以使用locale.currency
,设置标志grouping
:
<强>代码强>
import locale
locale.setlocale( locale.LC_ALL, '' )
locale.currency( 1234567.89, grouping = True )
<强>输出强>
'Portuguese_Brazil.1252'
'R$ 1.234.567,89'
我敢肯定,必须有这样的标准库函数,但它是有趣的尝试使用递归所以在这里把它写我自己就是我想出了:
def intToStringWithCommas(x):
if type(x) is not int and type(x) is not long:
raise TypeError("Not an integer!")
if x < 0:
return '-' + intToStringWithCommas(-x)
elif x < 1000:
return str(x)
else:
return intToStringWithCommas(x / 1000) + ',' + '%03d' % (x % 1000)
说了这么多,如果别人没有找到一个标准的方式来做到这一点,你应该使用来代替。
从评论一>到的ActiveState配方 498181 我此返工:
import re
def thous(x, sep=',', dot='.'):
num, _, frac = str(x).partition(dot)
num = re.sub(r'(\d{3})(?=\d)', r'\1'+sep, num[::-1])[::-1]
if frac:
num += dot + frac
return num
它使用正则表达式功能:先行即(?=\d)
确保只有组有一个数字“后”他们得到一个逗号三位数。我说“后”,因为该字符串是在这一点上反向。
[::-1]
只是反转的字符串。
稍微扩展伊恩施耐德的答案:
如果你想使用自定义千位分隔符,最简单的解决方法是:
'{:,}'.format(value).replace(',', your_custom_thousands_separator)
实施例
'{:,.2f}'.format(123456789.012345).replace(',', ' ')
如果你想这样的德国人表示,问题就变得更复杂一点:
('{:,.2f}'.format(123456789.012345)
.replace(',', ' ') # 'save' the thousands separators
.replace('.', ',') # dot to comma
.replace(' ', '.')) # thousand separators to dot
的的Python 3 强>
-
<强>整数(无小数):强>
"{:,d}".format(1234567)
-
<强>浮标(十进制):强>
"{:,.2f}".format(1234567)
其中f
前的数字指定的小数位的数量。
-
<强>加成强>
为印度万卢比快速和肮脏的起动器功能/亿卢比编号系统(12,34,567):
接受的答案是好的,但其实我更喜欢format(number,',')
。我更容易理解和记忆。
从Python版2.6你可以这样做:
def format_builtin(n):
return format(n, ',')
为蟒蛇的版本 < 2.6和只是为了你的信息了,这里有2手册的解决方案,他们把漂到整数,但负数正常工作:
def format_number_using_lists(number):
string = '%d' % number
result_list = list(string)
indexes = range(len(string))
for index in indexes[::-3][1:]:
if result_list[index] != '-':
result_list.insert(index+1, ',')
return ''.join(result_list)
几件事情的通知:
- 这一行: string='%d'%号 精美的转换成数字符串,它支持阴性和降级分从漂浮,使他们整数;
- 这片 索引[::-3] 返回每第三个项目从开始 最终,所以我用一片 [1:] 删除最后一项 因为我不需要一个逗号之后的最后一个号码;
- 这个条件 如果我[指标]!= '-' 正在用于支持负数,不插入一个逗号后的减的迹象。
和更多的铁杆的版本:
def format_number_using_generators_and_list_comprehensions(number):
string = '%d' % number
generator = reversed(
[
value+',' if (index!=0 and value!='-' and index%3==0) else value
for index,value in enumerate(reversed(string))
]
)
return ''.join(generator)
下面是一个用于花车太作品:
def float2comma(f):
s = str(abs(f)) # Convert to a string
decimalposition = s.find(".") # Look for decimal point
if decimalposition == -1:
decimalposition = len(s) # If no decimal, then just work from the end
out = ""
for i in range(decimalposition+1, len(s)): # do the decimal
if not (i-decimalposition-1) % 3 and i-decimalposition-1: out = out+","
out = out+s[i]
if len(out):
out = "."+out # add the decimal point if necessary
for i in range(decimalposition-1,-1,-1): # working backwards from decimal point
if not (decimalposition-i-1) % 3 and decimalposition-i-1: out = ","+out
out = s[i]+out
if f < 0:
out = "-"+out
return out
用法示例:
>>> float2comma(10000.1111)
'10,000.111,1'
>>> float2comma(656565.122)
'656,565.122'
>>> float2comma(-656565.122)
'-656,565.122'
用于Python 2.5+一个衬里和Python 3(正INT只):
''.join(reversed([x + (',' if i and not i % 3 else '') for i, x in enumerate(reversed(str(1234567)))]))
我Python初学者,但是有经验的程序员。我Python3.5,所以我只能使用逗号,但这仍然是一个有趣的方案拟订工作.考虑的情况下,未签名的整数。最可读Python程序用于增加成千上万分离似乎是:
def add_commas(instr):
out = [instr[0]]
for i in range(1, len(instr)):
if (len(instr) - i) % 3 == 0:
out.append(',')
out.append(instr[i])
return ''.join(out)
它还可以使用一列理解:
add_commas(instr):
rng = reversed(range(1, len(instr) + (len(instr) - 1)//3 + 1))
out = [',' if j%4 == 0 else instr[-(j - j//4)] for j in rng]
return ''.join(out)
这是较短,可能是一个衬垫,但是你将要做一些精神体操理解为什么它的工作。在这两种情况下我们会得到:
for i in range(1, 11):
instr = '1234567890'[:i]
print(instr, add_commas(instr))
1 1
12 12
123 123
1234 1,234
12345 12,345
123456 123,456
1234567 1,234,567
12345678 12,345,678
123456789 123,456,789
1234567890 1,234,567,890
第一个版本是更明智的选择,如果你想的程序加以理解。
此烘焙成每PEP蟒 - > HTTPS://www.python .ORG的/ dev / PEPS / PEP-0378 /
只是使用格式(1000, 'd'),以显示与千位分隔的整数
有在PEP描述的更多的格式,必须在它
这确实钱与逗号沿
def format_money(money, presym='$', postsym=''):
fmt = '%0.2f' % money
dot = string.find(fmt, '.')
ret = []
if money < 0 :
ret.append('(')
p0 = 1
else :
p0 = 0
ret.append(presym)
p1 = (dot-p0) % 3 + p0
while True :
ret.append(fmt[p0:p1])
if p1 == dot : break
ret.append(',')
p0 = p1
p1 += 3
ret.append(fmt[dot:]) # decimals
ret.append(postsym)
if money < 0 : ret.append(')')
return ''.join(ret)
我有一个Python 2和Python 3版本代码。我知道这个问题是问蟒蛇2,但现在(8年后笑)人们可能会被使用python 3.搜索结果的Python 3代码:
import random
number = str(random.randint(1, 10000000))
comma_placement = 4
print('The original number is: {}. '.format(number))
while True:
if len(number) % 3 == 0:
for i in range(0, len(number) // 3 - 1):
number = number[0:len(number) - comma_placement + 1] + ',' + number[len(number) - comma_placement + 1:]
comma_placement = comma_placement + 4
else:
for i in range(0, len(number) // 3):
number = number[0:len(number) - comma_placement + 1] + ',' + number[len(number) - comma_placement + 1:]
break
print('The new and improved number is: {}'.format(number))
,点击 Python 2的代码:(。编辑蟒蛇2的代码不工作,我想,语法是不同的)。
import random
number = str(random.randint(1, 10000000))
comma_placement = 4
print 'The original number is: %s.' % (number)
while True:
if len(number) % 3 == 0:
for i in range(0, len(number) // 3 - 1):
number = number[0:len(number) - comma_placement + 1] + ',' + number[len(number) - comma_placement + 1:]
comma_placement = comma_placement + 4
else:
for i in range(0, len(number) // 3):
number = number[0:len(number) - comma_placement + 1] + ',' + number[len(number) - comma_placement + 1:]
break
print 'The new and improved number is: %s.' % (number)
我使用python 2.5,所以我不能够访问内置的格式。
我看着Django的代码intcomma(代码intcomma_recurs下文),并意识到这是低效的,因为它是递归的,也编译在每次运行的正则表达式是不是一件好事要么。这是没有必要的“问题”作为Django是不是真的那么专注于这种低级别的性能。此外,我期待在性能10差的一个因素,但它只有3倍慢。
出于好奇,我实现intcomma了几个版本,看看有什么性能优势是使用正则表达式时。我的测试数据得出的微弱优势完成这个任务,但令人惊讶的不多的。
我也很高兴地看到我的怀疑:使用反向的xrange办法是在没有正则表达式的情况下是不必要的,但它确实使代码看的成本〜稍好的10%的性能。
。另外,我假设你正在传递一个字符串,看起来有点像一个数字。结果否则未定。
from __future__ import with_statement
from contextlib import contextmanager
import re,time
re_first_num = re.compile(r"\d")
def intcomma_noregex(value):
end_offset, start_digit, period = len(value),re_first_num.search(value).start(),value.rfind('.')
if period == -1:
period=end_offset
segments,_from_index,leftover = [],0,(period-start_digit) % 3
for _index in xrange(start_digit+3 if not leftover else start_digit+leftover,period,3):
segments.append(value[_from_index:_index])
_from_index=_index
if not segments:
return value
segments.append(value[_from_index:])
return ','.join(segments)
def intcomma_noregex_reversed(value):
end_offset, start_digit, period = len(value),re_first_num.search(value).start(),value.rfind('.')
if period == -1:
period=end_offset
_from_index,segments = end_offset,[]
for _index in xrange(period-3,start_digit,-3):
segments.append(value[_index:_from_index])
_from_index=_index
if not segments:
return value
segments.append(value[:_from_index])
return ','.join(reversed(segments))
re_3digits = re.compile(r'(?<=\d)\d{3}(?!\d)')
def intcomma(value):
segments,last_endoffset=[],len(value)
while last_endoffset > 3:
digit_group = re_3digits.search(value,0,last_endoffset)
if not digit_group:
break
segments.append(value[digit_group.start():last_endoffset])
last_endoffset=digit_group.start()
if not segments:
return value
if last_endoffset:
segments.append(value[:last_endoffset])
return ','.join(reversed(segments))
def intcomma_recurs(value):
"""
Converts an integer to a string containing commas every three digits.
For example, 3000 becomes '3,000' and 45000 becomes '45,000'.
"""
new = re.sub("^(-?\d+)(\d{3})", '\g<1>,\g<2>', str(value))
if value == new:
return new
else:
return intcomma(new)
@contextmanager
def timed(save_time_func):
begin=time.time()
try:
yield
finally:
save_time_func(time.time()-begin)
def testset_xsimple(func):
func('5')
def testset_simple(func):
func('567')
def testset_onecomma(func):
func('567890')
def testset_complex(func):
func('-1234567.024')
def testset_average(func):
func('-1234567.024')
func('567')
func('5674')
if __name__ == '__main__':
print 'Test results:'
for test_data in ('5','567','1234','1234.56','-253892.045'):
for func in (intcomma,intcomma_noregex,intcomma_noregex_reversed,intcomma_recurs):
print func.__name__,test_data,func(test_data)
times=[]
def overhead(x):
pass
for test_run in xrange(1,4):
for func in (intcomma,intcomma_noregex,intcomma_noregex_reversed,intcomma_recurs,overhead):
for testset in (testset_xsimple,testset_simple,testset_onecomma,testset_complex,testset_average):
for x in xrange(1000): # prime the test
testset(func)
with timed(lambda x:times.append(((test_run,func,testset),x))):
for x in xrange(50000):
testset(func)
for (test_run,func,testset),_delta in times:
print test_run,func.__name__,testset.__name__,_delta
和这里是测试结果:
intcomma 5 5
intcomma_noregex 5 5
intcomma_noregex_reversed 5 5
intcomma_recurs 5 5
intcomma 567 567
intcomma_noregex 567 567
intcomma_noregex_reversed 567 567
intcomma_recurs 567 567
intcomma 1234 1,234
intcomma_noregex 1234 1,234
intcomma_noregex_reversed 1234 1,234
intcomma_recurs 1234 1,234
intcomma 1234.56 1,234.56
intcomma_noregex 1234.56 1,234.56
intcomma_noregex_reversed 1234.56 1,234.56
intcomma_recurs 1234.56 1,234.56
intcomma -253892.045 -253,892.045
intcomma_noregex -253892.045 -253,892.045
intcomma_noregex_reversed -253892.045 -253,892.045
intcomma_recurs -253892.045 -253,892.045
1 intcomma testset_xsimple 0.0410001277924
1 intcomma testset_simple 0.0369999408722
1 intcomma testset_onecomma 0.213000059128
1 intcomma testset_complex 0.296000003815
1 intcomma testset_average 0.503000020981
1 intcomma_noregex testset_xsimple 0.134000062943
1 intcomma_noregex testset_simple 0.134999990463
1 intcomma_noregex testset_onecomma 0.190999984741
1 intcomma_noregex testset_complex 0.209000110626
1 intcomma_noregex testset_average 0.513000011444
1 intcomma_noregex_reversed testset_xsimple 0.124000072479
1 intcomma_noregex_reversed testset_simple 0.12700009346
1 intcomma_noregex_reversed testset_onecomma 0.230000019073
1 intcomma_noregex_reversed testset_complex 0.236999988556
1 intcomma_noregex_reversed testset_average 0.56299996376
1 intcomma_recurs testset_xsimple 0.348000049591
1 intcomma_recurs testset_simple 0.34600019455
1 intcomma_recurs testset_onecomma 0.625
1 intcomma_recurs testset_complex 0.773999929428
1 intcomma_recurs testset_average 1.6890001297
1 overhead testset_xsimple 0.0179998874664
1 overhead testset_simple 0.0190000534058
1 overhead testset_onecomma 0.0190000534058
1 overhead testset_complex 0.0190000534058
1 overhead testset_average 0.0309998989105
2 intcomma testset_xsimple 0.0360000133514
2 intcomma testset_simple 0.0369999408722
2 intcomma testset_onecomma 0.207999944687
2 intcomma testset_complex 0.302000045776
2 intcomma testset_average 0.523000001907
2 intcomma_noregex testset_xsimple 0.139999866486
2 intcomma_noregex testset_simple 0.141000032425
2 intcomma_noregex testset_onecomma 0.203999996185
2 intcomma_noregex testset_complex 0.200999975204
2 intcomma_noregex testset_average 0.523000001907
2 intcomma_noregex_reversed testset_xsimple 0.130000114441
2 intcomma_noregex_reversed testset_simple 0.129999876022
2 intcomma_noregex_reversed testset_onecomma 0.236000061035
2 intcomma_noregex_reversed testset_complex 0.241999864578
2 intcomma_noregex_reversed testset_average 0.582999944687
2 intcomma_recurs testset_xsimple 0.351000070572
2 intcomma_recurs testset_simple 0.352999925613
2 intcomma_recurs testset_onecomma 0.648999929428
2 intcomma_recurs testset_complex 0.808000087738
2 intcomma_recurs testset_average 1.81900000572
2 overhead testset_xsimple 0.0189998149872
2 overhead testset_simple 0.0189998149872
2 overhead testset_onecomma 0.0190000534058
2 overhead testset_complex 0.0179998874664
2 overhead testset_average 0.0299999713898
3 intcomma testset_xsimple 0.0360000133514
3 intcomma testset_simple 0.0360000133514
3 intcomma testset_onecomma 0.210000038147
3 intcomma testset_complex 0.305999994278
3 intcomma testset_average 0.493000030518
3 intcomma_noregex testset_xsimple 0.131999969482
3 intcomma_noregex testset_simple 0.136000156403
3 intcomma_noregex testset_onecomma 0.192999839783
3 intcomma_noregex testset_complex 0.202000141144
3 intcomma_noregex testset_average 0.509999990463
3 intcomma_noregex_reversed testset_xsimple 0.125999927521
3 intcomma_noregex_reversed testset_simple 0.126999855042
3 intcomma_noregex_reversed testset_onecomma 0.235999822617
3 intcomma_noregex_reversed testset_complex 0.243000030518
3 intcomma_noregex_reversed testset_average 0.56200003624
3 intcomma_recurs testset_xsimple 0.337000131607
3 intcomma_recurs testset_simple 0.342000007629
3 intcomma_recurs testset_onecomma 0.609999895096
3 intcomma_recurs testset_complex 0.75
3 intcomma_recurs testset_average 1.68300008774
3 overhead testset_xsimple 0.0189998149872
3 overhead testset_simple 0.018000125885
3 overhead testset_onecomma 0.018000125885
3 overhead testset_complex 0.0179998874664
3 overhead testset_average 0.0299999713898
意大利号码: '' 千个分离器是
我解决了它这样...一个dictonary
from random import randint
voci = {
"immobilizzazioni": randint(200000, 500000),
"tfr": randint(10000, 25000),
"ac": randint(150000, 200000),
"fondo": randint(10500, 22350),
"debiti": randint(150000, 250000),
"ratei_attivi": randint(2000, 2500),
"ratei_passivi": randint(1500, 2600),
"crediti_v_soci": randint(10000, 30000)
}
testo_rnd2 = """Nell’azienda Hypermax S.p.a. di Bologna le immobilizzazioni valgono {immobilizzazioni:,} €, i debiti per TFR sono pari a {tfr:,} €, l’attivo circolante è di {ac:,} euro, il fondo rischi ed oneri ha un importo pari a {fondo:,} euro, i debiti sono {debiti:,} €, i ratei e risconti attivi sono pari a {ratei_attivi:,} euro, i ratei e risconti passivi sono pari a {ratei_passivi:,} euro. I crediti verso i soci sono pari a {crediti_v_soci:,} euro."""
print(testo_rnd2)
出: 乐immobilizzazioni valgono 419.168€。我debiti每TFR索诺彩一13.255€。 L'attivo circolante E DI'195.443欧元。金正日丰多rischi版oneri公顷未importo彩一13.374欧元。我debiti索诺180.947€。我rateièrisconti attivi索诺彩一2.271欧元。我rateièrisconti passivi索诺彩一1.864欧元。我crediti反面我SOCI是sono帕里一个17.630欧元。
下面是使用另一种变型发电机功能,对于整数工作的:
def ncomma(num):
def _helper(num):
# assert isinstance(numstr, basestring)
numstr = '%d' % num
for ii, digit in enumerate(reversed(numstr)):
if ii and ii % 3 == 0 and digit.isdigit():
yield ','
yield digit
return ''.join(reversed([n for n in _helper(num)]))
和这是一个测试:
>>> for i in (0, 99, 999, 9999, 999999, 1000000, -1, -111, -1111, -111111, -1000000):
... print i, ncomma(i)
...
0 0
99 99
999 999
9999 9,999
999999 999,999
1000000 1,000,000
-1 -1
-111 -111
-1111 -1,111
-111111 -111,111
-1000000 -1,000,000
只要子类long
(或float
,或其他)。这是非常实用的,因为这样一来,你仍然可以在数学OPS(因此现有的代码)使用你的号码,但他们会在你的终端所有打印好听。
>>> class number(long):
def __init__(self, value):
self = value
def __repr__(self):
s = str(self)
l = [x for x in s if x in '1234567890']
for x in reversed(range(len(s)-1)[::3]):
l.insert(-x, ',')
l = ''.join(l[1:])
return ('-'+l if self < 0 else l)
>>> number(-100000)
-100,000
>>> number(-100)
-100
>>> number(-12345)
-12,345
>>> number(928374)
928,374
>>> 345
我喜欢真正的项目基于地区的解决方案,但我认为与使用切片分配的方式应该是这里所说的:
def format_money(f, delimiter=',', frac_digits=2):
negative_fix = int(f < 0)
s = '%.*f' % (frac_digits, f)
if len(s) < 5 + frac_digits + negative_fix:
return s
l = list(s)
l_fix = l[negative_fix:]
p = len(l_fix) - frac_digits - 5
l_fix[p::-3] = [i + delimiter for i in l_fix[p::-3]]
return ''.join(l[:negative_fix] + l_fix)
主旨与文档测试是在这里 - https://gist.github.com/ei-grad / b290dc761ae253af69438bbb94d82683
有关浮体:
float(filter(lambda x: x!=',', '1,234.52'))
# returns 1234.52
有关整数:
int(filter(lambda x: x!=',', '1,234'))
# returns 1234
如果你不想依赖任何外部库:
s = str(1234567)
print ','.join([s[::-1][k:k+3][::-1] for k in xrange(len(s)-1, -1, -3)])
这仅适用于非负整数。