在字符串末尾递增数字 [英] Incrementing a number at the end of string

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

问题描述

我正在尝试解决一个问题,即在字符串的末尾添加1.意思是:

I am trying to solve a problem which says, to add 1 at the end of a string. Which means:

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 ,但我不知道如何解决:

The code gives me this Output: abcd099100 and I don't know how to solve it:

推荐答案

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

Match all digits at the end of string with [0-9]+$ and use re.sub with a callable as the replacement argument:

import re
def increment_string(strng):
    return re.sub(r'[0-9]+$', lambda x: f"{str(int(x.group())+1).zfill(len(x.group()))}", strng)

print(increment_string("abcd99"))
# => abcd100
print(increment_string("abcd099"))
# => abcd100
print(increment_string("abcd001"))
# => abcd002

请参见 Python演示

这篇关于在字符串末尾递增数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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