因为英语语言中,数字每3位,就有一个单独的单词,hundred, thousand等。所以,英文里面有很多数字都是用逗号分隔开来的。这样便于阅读,也便于一下子就看数字的数量级大小。
下面是麦新杰练习Python编程时,写的一个将数字转换为逗号分隔形式的字符串的函数,这个函数支持输入负数。代码如下:
def Int2StrByComma(ii):
""" Convert a integer to a comma separated string
"""
if type(ii) is not int: # int is also long right now in Python
return False # return a boolean
strii = str(ii) # to string, we can not directly change every single char in a string
if ii > 0:
strii = '+' + strii
result = ''
cc = 0
for i in range(len(strii),1,-1):
if cc == 3:
result = ',' + result
cc = 0
result = strii[i-1] + result # index starts from 0
cc += 1
else: # after the loop is over
if strii[0] == '-':
result = strii[0] + result # negative sign
return result # return a string
#---- End of Function: Int2StrByComma
测试这个函数的时候,发现Python一个有趣的,但是也许会很有用的一个特性,不好用语言表述,请看下面:
>>>
>>> za.Int2StrByComma(---12345678)
'-12,345,678'
>>>
>>>
>>> za.Int2StrByComma(----12345678)
'12,345,678'
>>>
>>> za.Int2StrByComma(--+++--12345678)
'12,345,678'
>>> za.Int2StrByComma(--+-++--12345678)
'-12,345,678'
>>>
>>> za.Int2StrByComma(--+-++--0)
''
>>> za.Int2StrByComma(--+-++--0000000)
''
>>>
>>>
>>> str(---123)
'-123'
>>>
>>> str(---000)
'0'
简单的说,就是正号负号直接相互抵消,多余的0也当成一个0处理,0之前不会有负号。