增加 Python 字符串中的最后一位数字 [英] Incrementing the last digit in a Python string

查看:81
本文介绍了增加 Python 字符串中的最后一位数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 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.com">>>re.sub('(\d+)(?!\d)', lambda x: str(int(x.group(0)) + 1), s)'f.bar-30.domain.com'

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.com"
>>> re.sub('(\d+)(?!\d)', lambda x: str(int(x.group(0)) + 1), s)
'f.bar-30.domain.com'

这篇关于增加 Python 字符串中的最后一位数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆