I'm interpreting your question as "I have a string ending in a digit sequence, for example "item_01"
. I want to get a string with the same form as the original string, but with the digit incremented by one, for example "item_02"
."
You could use re.sub
to replace the digit sequence with a new one:
>>> import re
>>>
>>> s = "item_01"
>>> result = re.sub(
... r"\d+$", #find all digits at the end of the string,
... lambda m: str( #replacing them with a string
... int(m.group())+1 #equal to one plus the original value,
... ).zfill(len(m.group())), #with at least as much padding as the original value.
... s
... )
>>>
>>> print(result)
item_02
In one line, that would be
result = re.sub(r"\d+$", lambda m: str(int(m.group())+1).zfill(len(m.group())), s)
Note that the resulting string may be longer than the original string, if the original value is all nines:
>>> re.sub(r"\d+$", lambda m: str(int(m.group())+1).zfill(len(m.group())), "item_99")
'item_100'
And it will only increment the digit sequence at the very end of the string, and not any intermediary sequences.
>>> re.sub(r"\d+$", lambda m: str(int(m.group())+1).zfill(len(m.group())), "item_23_42")
'item_23_43'
And if the string has no suffix digit sequence, it will simply return the original value unaltered.
>>> re.sub(r"\d+$", lambda m: str(int(m.group())+1).zfill(len(m.group())), "item_foobar")
'item_foobar'