把数字翻译成字符串python_用Python实现将数字转换为逗号分隔形式的字符串

因为英语语言中,数字每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之前不会有负号。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值