好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Python写一个字符串数字后缀部分的递增函数

需求:

Python处理重名字符串,添加或递增数字字符串后缀

对于2个重名的字符串,添加数字后缀,比如两个重复的字符串 s1 = [name] , s2 = [name] ,将s2的名称设置为 name_1 对应3个或多个重名的字符串,数字部分实现递增,初始时 s1=s2=s3=[name ],重命名后得到 s1=[name] , s2=[name_1] , s3=[name_2 ]

要灵活处理字符串问题,使用re模块最为方便下面是一个对带有下划线+数字的后缀字符串递增的方法

def increase_string_suffix(s, incr_num=1):
? ? """
? ? 带数字后缀"_d"的字符串自增方法,"name_1" 自增1 --> "name_2"
? ? Example
? ? -----------------
? ? >>> s = "name_01"
? ? >>> increase_string_suffix(s, incr_num=2)
? ? 'name_03'
? ? """
? ? suffix_searched = re.search(r"(_)(\d+)$", s)
? ? if suffix_searched:
? ? ? ? suffix_plus_1 = re.sub(
? ? ? ? ? ? r"(_)(\d+)$",
? ? ? ? ? ? lambda x: f"{x.group(1)}{str(int(x.group(2)) + incr_num).zfill(len(x.group(2)))}",
? ? ? ? ? ? s
? ? ? ? )
? ? else:
? ? ? ? suffix_plus_1 = f"{s}_1"
? ? return suffix_plus_1

也可以写一个递减的,或是修改前缀的,

例如:

def increase_string_prefix(s, incr_num=1):
? ? """
? ? 带数字前缀"d-"的字符串自增方法,"1-name" 自增1 --> "2-name"
? ? Example
? ? -----------------
? ? >>> s = "1-name"
? ? >>> increase_string_prefix(s, incr_num=1)
? ? '2-name'
? ? """
? ? prefix_searched = re.search(r"^(\d+)(-)", s)
? ? if prefix_searched:
? ? ? ? prefix_plus_1 = re.sub(
? ? ? ? ? ? r"^(\d+)(-)",
? ? ? ? ? ? lambda x: f"{str(int(x.groups()[0]) + incr_num).zfill(len(x.groups()[0]))}{x.groups()[1]}",
? ? ? ? ? ? s
? ? ? ? )
? ? else:
? ? ? ? prefix_plus_1 = f"1-{s}"
? ? return prefix_plus_1

对于更多的正则表达式使用方法,可以参考之前的 这篇文章

到此这篇关于Python写一个字符串数字后缀部分的递增函数的文章就介绍到这了,更多相关Python递增函数内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

查看更多关于Python写一个字符串数字后缀部分的递增函数的详细内容...

  阅读:45次