我想在 Python 2.7 中增加用户提供的字符串的最后一位数字.
我可以像这样替换第一个数字:
def increment_hostname(name):尝试:number = re.search(r'\d+', name).group()除了属性错误:返回错误数字 = 整数(数字)+ 1数字 = str(数字)return re.sub(r'\d+', number, name)我可以用 re.findall 匹配所有数字,然后增加列表中的最后一个数字,但我不知道如何进行替换:
number = re.findall(r'\d+', name)数字 = 数字[-1]数字 = 整数(数字)+ 1数字 = str(数字) 解决方案使用 否定外观前面看到数字后面没有数字,传递一个函数给re.sub() 替换参数并增加其中的数字:
>>>进口重新>>>s = "foo 123 bar">>>re.sub('\d(?!\d)', lambda x: str(int(x.group(0)) + 1), s)'foo 124 酒吧'您可能还想以一种特殊的方式处理9,例如,将其替换为0:
>>>def repl(匹配):... 数字 = 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 酒吧'UPD(处理新示例):
>>>进口重新>>>s = "f.bar-29.domain">>>re.sub('(\d+)(?!\d)', lambda x: str(int(x.group(0)) + 1), s)'f.bar-30.domain'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)解决方案
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" >>> re.sub('(\d+)(?!\d)', lambda x: str(int(x.group(0)) + 1), s) 'f.bar-30.domain'
更多推荐
增加 Python 字符串中的最后一位数字
发布评论