String incrementer

https://www.codewars.com/kata/54a91a4883a7de5d7800009c

题目:

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.

题目大意:

将字符串最后的数字加1,如果没有数字就新增1,还要注意数字前面有0的话需注意位数;

测试用例:

Test.assert_equals(increment_string("foo"), "foo1")
Test.assert_equals(increment_string("foobar001"), "foobar002")
Test.assert_equals(increment_string("foobar1"), "foobar2")
Test.assert_equals(increment_string("foobar00"), "foobar01")
Test.assert_equals(increment_string("fo66obar99"), "fo66obar100")
Test.assert_equals(increment_string("foobar099"), "foobar100")
Test.assert_equals(increment_string(""), "1")

 

我的算法:

def increment_string(strng):
    import re
    match = re.search('(\d*)$',strng)
    num = match.group(0)
    if num:
        return strng[:-len(num)] + str(int(num)+1).zfill(len(num))
    else:
        return strng+'1'

大神的算法:

def increment_string(strng):
    head = strng.rstrip('0123456789')
    tail = strng[len(head):]
    if tail=='':
        return head+'1'
    return head + str(int(tail)+1).zfill(len(tail))

大神很巧妙的用了strip函数,将右侧的数字给过滤掉,而我只能想到用正则去匹配,

同时还学习到用zfill函数来用0补齐位数

 

 

你可能感兴趣的:(python,菜鸟练习,kata)