Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在字符串末尾递增一个数字_Python_Regex_String_List - Fatal编程技术网

Python 在字符串末尾递增一个数字

Python 在字符串末尾递增一个数字,python,regex,string,list,Python,Regex,String,List,我试图解决一个问题,在字符串末尾添加1。 这意味着: 1.abcd12将变成:abcd13 2.abcd099将变成abcd100 3.abcd01将变成abcd02 4.ddh^add@2204将变为ddh^add@2205 我的代码: import re def increment_string(strng): regex = re.compile(r'[0-9]') match = regex.findall(strng) nums = ''.join(m

我试图解决一个问题,在字符串末尾添加1。 这意味着:

1.abcd12将变成:abcd13

2.abcd099将变成abcd100

3.abcd01将变成abcd02

4.ddh^add@2204将变为ddh^add@2205

我的代码:

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

代码给了我这个输出:abcd099100我不知道如何解决它:

将字符串末尾的所有数字与
[0-9]+$
匹配,并使用
re.sub
和可调用参数作为替换参数:

重新导入
def增量_字符串(strng):
返回re.sub(r'[0-9]+$',lambda x:f“{str(int(x.group())+1).zfill(len(x.group()))}”,strng)
打印(增量字符串(“abcd99”))
#=>abcd100
打印(增量字符串(“abcd099”))
#=>abcd100
打印(增量字符串(“abcd001”))
#=>abcd002

请参见

将旧号码替换为”:

输出:

abcd100

嗯,您的代码从不尝试用新数字替换旧数字-它只是将新数字附加到字符串。因此,解决这一问题的方法是实际执行替换abcd1@AyushKumar但是你“foobar00应该变成foobar01”。我知道您需要保留位数。我只需要使用
if-else
语句来改进代码。谢谢你的回答
abcd100