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

Viewed 224

Why my code is wrong which outputs an error

def increment_string(strng):
   
    if strng == '':
        return '1'
    elif strng.isdigit():
        number= int(''.join(filter(str.isdigit,strng)))
        return re.sub('\d+',str(number +1),strng)

    
    return strng + str(1)

Output: increment_string("foobar001")

It should return 'foobar002' but it is returning 'foobar0011'

2 Answers

It gives 'foobar0011' because the program control is not entered into the elif block and it returned strng + str(1).

Program control not entered the elif block because the function strng.isdigit() returns false. This returns true only if each character in strng is a digit. My suggestion is to replace isdigit() function with the isalnum() function. Because isalnum() function verifies that each character in a string is either an alphabet or a digit.

Here is my solution :

import re

def increment_string(strng):
   
    if strng == '':
        return '1'

    elif strng.isalnum():
        number = int(''.join(filter(str.isdigit, strng)))
        return re.sub('\d+', str(number + 1), strng)

    return strng + str(1)

print(increment_string("foobar001"))

The problem with your code is explained below:

def increment_string(strng):
    #...
    ''' 
    this is checking if the passed string is a digit. Since you are
    passing "foobar001", which is not a digit, elif condition is not executed,
    and goes directly to the last return statement where you simple add "1" to the string
    '''
    elif strng.isdigit():
        #...
    
    return strng + str(1)

To meet the requirements given in the question, try this out:

def increment_string(strng):
    match = re.search('(\d+)', strng)
    if match:
        num = match.group(1)
        newNum = str(int(num) + 1)
        return re.sub('\d+', str(newNum.zfill(len(num))), strng)
    else:
        return strng

Note : This returns the same input string in case no number is present.

To know more about zfill, check here.

Related