字符串索引超出范围,Python

时间:2017-07-30 14:07:13

标签: python-3.x

用于递增字符串的函数的代码,以创建新字符串。如果字符串已经以数字结尾,则该数字应增加1.如果字符串不以数字结尾,则应将数字1附加到新字符串。

输出正确,但显示String index out of range错误。有人可以帮我解决字符串索引在何处以及如何超出范围?

测试用例,预期输出: (increment_string(" foo")," foo1"),(increment_string(" foobar001")," foobar002"),(increment_string(& #34; foobar1")," foobar2"),(increment_string(" foobar00")," foobar01"),(" foobar99" ;)," foobar100"),(" foobar099")," foobar100"),(increment_string(""),&#34 1#34)

def increment_string(strng):
   if strng[-1].isdigit():
      exp_strng=strng[::-1]
      new_strng=""
      new_strng1=""
      for i in exp_strng:
         if i.isdigit():
            new_strng+=i
         else:
            break
      new_strng=new_strng[::-1]
      new_strng1=int(new_strng)+1
      new_strng1='{num:{fill}{width}}'.format(num=new_strng1, fill='0', width=len(new_strng))
      return(strng[:-len(new_strng)]+new_strng1)

   else:
      strng+="1"
      return(strng)

3 个答案:

答案 0 :(得分:2)

如果认为这可以更好地解决您的问题:

from re import search

def increment_string(s):
    number = search('\d+$', s)
    if number != None:
        number = number.group()
        first_part = s.split(number)[0]
        return first_part + str(int(number)+1)
    else:
        return s + '1'

当数字为9时,我不知道你想要什么:0或10.这段代码产生10。

答案 1 :(得分:2)

由于您向我们提供了有关给定测试用例的更多信息,因此您可以通过修改if语句来绕过空字符串的边缘情况:

def increment_string(strng):
   # Add it here #
   if strng == "":
      return "1"

   elif strng[-1].isdigit():
      exp_strng = strng[::-1]
      new_strng = ""
      new_strng1 = ""
      for i in exp_strng:
         if i.isdigit():
            new_strng += i
         else:
            break
      new_strng = new_strng[::-1]
      new_strng1 = int(new_strng) + 1
      new_strng1 = '{num:{fill}{width}}'.format(num=new_strng1, fill='0', width=len(new_strng))
      return strng[:-len(new_strng)] + new_strng1

   else:
      strng += "1"
      return strng

答案 2 :(得分:-1)

传递空字符串时导致错误。并且我通过另外添加一个来解决它:(感谢Skam)

def increment_string(strng):
if len(strng)>0:
    if strng[-1].isdigit():
        exp_strng=strng[::-1]
        new_strng=""
        new_strng=""
        for i in exp_strng:
            if i.isdigit():
                new_strng+=i
            else:
                break
        new_strng=new_strng[::-1]
        new_strng1=int(new_strng)+1
        new_strng1=str(new_strng1)
        new_strng1=new_strng1.zfill(len(new_strng))
        return(strng[:-len(new_strng)]+new_strng1)
    else:
        strng+="1"
        return(strng)
else:
    strng+="1"
    return(strng)