python 字符串 负数_在Python中使用负数分割字符串时,0被禁用?

假设我有一根绳子:>>>a = 'akwkwas'

>>>

>>>a[-3:]

'was'

>>>a[-3:None]

'was'

>>>a[-3:0]

''

为什么我不能用0作为切片的结尾?

这是来自文档:One way to remember how slices work is to think of the indices as pointing between characters, with the left edge of the first character numbered 0. Then the right edge of the last character of a string of n characters has index n, for example:+---+---+---+---+---+---+

| P | y | t | h | o | n |

+---+---+---+---+---+---+

0 1 2 3 4 5 6

-6 -5 -4 -3 -2 -1The first row of numbers gives the position of the indices 0...6 in the string; the second row gives the corresponding negative indices. The slice from i to j consists of all characters between the edges labeled i and j, respectively.

因此,当我们在循环中使用负索引时,我们应该检查结束值,因为负索引中的结束0不存在,例如当我们将字符串拆分为类似金钱的字符串时:>>>a = '12349878334'

>>>print(','.join([a[-i-3:-i if i else None] for i in range(0, len(a), 3)][::-1]))

>>>12,349,878,334

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值