Incrementing the last digit in a Python string

2020-07-31 19:36发布

问题:

I'd like to increment the last digit of user provided string in Python 2.7.

I can replace the first digit like this:

def increment_hostname(name):
    try:
        number = re.search(r'\d+', name).group() 
    except AttributeError:
        return False            
    number = int(number) + 1
    number = str(number)
    return re.sub(r'\d+', number, name)       

I can match all the digits with re.findall then increment the last digit in the list but I'm not sure how to do the replace:

number = re.findall(r'\d+', name)     
number = numbers[-1]
number = int(number) + 1                      
number = str(number)

回答1:

Use negative look ahead to see that there are no digits after a digit, pass a function to the re.sub() replacement argument and increment the digit in it:

>>> import re
>>> s = "foo 123 bar"
>>> re.sub('\d(?!\d)', lambda x: str(int(x.group(0)) + 1), s)
'foo 124 bar'

You may also want to handle 9 in a special way, for example, replace it with 0:

>>> def repl(match):
...     digit = int(match.group(0))
...     return str(digit + 1 if digit != 9 else 0)
... 
>>> s = "foo 789 bar"
>>> re.sub('\d(?!\d)', repl, s)
'foo 780 bar'

UPD (handling the new example):

>>> import re
>>> s = "f.bar-29.domain.com"
>>> re.sub('(\d+)(?!\d)', lambda x: str(int(x.group(0)) + 1), s)
'f.bar-30.domain.com'