Ayush Kumar
Ayush Kumar

Reputation: 532

Incrementing a number at the end of string

I am trying to solve a problem which says, to add 1 at the end of a string. Which means:

1.abcd12 will become: abcd13

2.abcd099 will become abcd100

3.abcd01 will become abcd02

4.ddh^add@2204 will become ddh^add@2205

My code:

import re
def increment_string(strng):
    regex = re.compile(r'[0-9]')
    match = regex.findall(strng)
    
    nums = ''.join(match[-3:])
    
    add = int(nums)+1
    print(strng+str(add))
increment_string("abcd99")

The code gives me this Output: abcd099100 and I don't know how to solve it:

Upvotes: 3

Views: 148

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626748

Match all digits at the end of string with [0-9]+$ and use re.sub with a callable as the replacement argument:

import re
def increment_string(strng):
    return re.sub(r'[0-9]+$', lambda x: f"{str(int(x.group())+1).zfill(len(x.group()))}", strng)

print(increment_string("abcd99"))
# => abcd100
print(increment_string("abcd099"))
# => abcd100
print(increment_string("abcd001"))
# => abcd002

See the Python demo

Upvotes: 1

Sushil
Sushil

Reputation: 5531

Replace the old number with '':

import re


def increment_string(strng):
    regex = re.compile(r'[0-9]')
    match = regex.findall(strng)

    nums = ''.join(match[-3:])
    strng = strng.replace(nums, '')
    add = int(nums) + 1

    print(strng + str(add))


increment_string("abcd99")

Output:

abcd100

Upvotes: 1

Related Questions