【Kata Daily 190903】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.

------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

谷歌翻译:

您的工作是编写一个增加字符串的函数,以创建一个新字符串。

  • 如果字符串已经以数字结尾,则该数字应增加1。
  • 如果字符串没有以数字结尾。数字1应该附加到新字符串。

例子:

foo -> foo1

foobar23 -> foobar24

foo0042 -> foo0043

foo9 -> foo10

foo099 -> foo100

注意:如果数字有前导零,则应考虑数字位数

------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

个人解决思路:

  从字符串的末尾开始,遇到数字就继续遍历,遇到非数字就停止。将数字部分加1,再和没有遍历到的组合。最后考虑特殊情况。

def increment_string(strng):
    L = []
    global strng1
    strng1 = ""
    if len(strng)==0:#特殊情况,处理strng为空时
        strng = "1"
    else:
        if not strng[-1].isdigit():#特殊情况,处理最后一位不是数字时
            strng = strng + "1"
        else:
            for i in reversed(strng):#反向遍历
                if i.isdigit():
                    L.append(i)
                else:
                    strng1 = strng[0:-len(L)]#切片
                    break
            s1 = "".join(reversed(L))#列表转化为字符串
            s2 = str(int(s1)+1).zfill(len(L))#zfill是自动补零
            strng = strng1 + s2
    return strng

优质解答:

def increment_string(strng):
    head = strng.rstrip('0123456789')#获取左边非数字部分
    tail = strng[len(head):]#获取右边剩下的一部分
    if tail == "": return strng+"1"
    return head + str(int(tail) + 1).zfill(len(tail))

知识点:

len(s):

返回对象(字符、列表、元组等)长度或项目个数。

切片:

L[开始索引, 结束索引, 相隔取数],默认相隔取数为1。取值不含结束索引

L = list(range(10))
L1 = L[0:3]#从索引0开始取到索引3为止,不包含3
#运行结果:[0, 1, 2]

L2 = L[:3]#也是从索引0开始,同L1
#运行结果:[0, 1, 2]

L3 = L[:]#复制一个一样的列表
#运行结果:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

L4 = L[0:6:2]#从索引0到索引6,没隔两个数取一个
#运行结果:[0, 2, 4]

L5 = L[::-1]#倒序取出全部的元素

L6 = L[:-1]#从索引0开始取到倒数第一个,不含倒数第一个
#运行结果:[0, 1, 2, 3, 4, 5, 6, 7, 8]

判断字符串类型:

1、str.isdigit():判断str是否是数字,返回布尔类型

2、str.isalpha():判断str是否是字母,返回布尔类型

3、str.isalnum():判断str是否是字母或数字的组合,返回布尔类型

reversed(L):

反向遍历,不作用于原来的list

字符串和列表转换:

1、字符串转列表:

  str.split("参数")#参数一般为空格

2、列表转字符串:

  "参数".join(L)#参数一般为空格

自动补零str.zfill(len):

zfill() 方法返回指定长度的字符串,原字符串右对齐,前面填充0。

去除头尾符号函数:

1、str.lstrip(str chars):根据参数值去除左边的符号

2、str.rstrip(str chars):根据参数值去除右边的符号

3、str.strip(str chars):根据参数值去除左右两边的符号

原文地址:https://www.cnblogs.com/bcaixl/p/11454006.html