【Codewars python 5kyu】: String incrementer

问题描述:

Your job is to write a function which increments a string, to create a new string.

  • If the string already ends with a number, the number should be incremented by 1.
  • If the string does not end with a number. the number 1 should be appended to the new string.

Examples:

foo -> foo1

foobar23 -> foobar24

foo0042 -> foo0043

foo9 -> foo10

foo099 -> foo100

Attention: If the number has leading zeros the amount of digits should be considered.

代码实现:

#codewars第十六题 (有错误)
def increment_string(strng):
    if strng == '': return '1'
    my_str = list(strng)
    _length = len(strng)
    num = 0
    n = 0
    for i in range(_length-1,-1,-1):
        if ord(strng[i]) >= 48 and ord(strng[i]) <= 57: #是数字(48-57) 继续
            if ord(strng[i]) == 48:  #如果是0
                num += 1
                if (num == 1) or (strng[i+1] == '9'):
                    my_str.pop(i)
                break
            else:
                num += int(strng[i])*pow(10,n)
                n += 1
                my_str.pop(i)
        else:
            num += 1
            break
    if n == _length: num += 1
    _length0 = len(my_str)
    ss = ''
    for j in range(0,_length0):
        ss = ss + my_str[j]
    return ss+str(num)

#另解
def increment_string(strng):
    head = strng.rstrip('0123456789')  #删除 string 字符串末尾的指定字符(默认为空格). '0123456789' 就是删除在0123456789中的值  只要有就删除
    tail = strng[len(head):]  #从头的结尾处开始取到最后 就是把后面的数字串取出来
    if tail=='':
        return head+'1'
    return head + str(int(tail)+1).zfill(len(tail)) #zfill方法返回指定长度的字符串(括号内为指定长度),原字符串右对齐,字符串长度不够,在字符串前面填充0。

increment_string("foo002")

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值