Incrementando um número no final da string

Nov 01 2020

Estou tentando resolver um problema que diz: adicionar 1 no final de uma string . Que significa:

1. abcd12 se tornará: abcd13

2. abcd099 se tornará abcd100

3. abcd01 se tornará abcd02

4. ddh ^ add @ 2204 se tornará ddh ^ add @ 2205

Meu código:

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")

O código me dá esta saída: abcd099100 e não sei como resolvê-lo:

Respostas

1 WiktorStribiżew Nov 01 2020 at 13:55

Combine todos os dígitos no final da string com [0-9]+$e use re.subcom um chamável como o argumento de substituição:

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

Veja a demonstração do Python

1 Sushil Nov 01 2020 at 13:56

Substitua o número antigo por '':

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")

Resultado:

abcd100