網站首頁 編程語言 正文
需求:
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
例子在代碼中可以直接運行注釋的doc部分,參數s是要傳入的字符串,incr_num是一次要增加的步數
代碼中核心部分是re.sub方法,r"(_)(\d+)$"是匹配搜尋部分,()對匹配的部分進行分組,x.group(1)是()匹配到的"",x.group(2)是匹配到的數字部分,zfill往左邊填0補上長度,例如01→02而不會是01→2
也可以寫一個遞減的,或是修改前綴的,
例如:
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
對于更多的正則表達式使用方法,可以參考之前的這篇文章
原文鏈接:https://blog.csdn.net/Moelimoe/article/details/122747365
相關推薦
- 2022-10-31 解決Python3中二叉樹前序遍歷的迭代問題_python
- 2022-09-25 MyBatis實現多表查詢(一對一、一對多)的方式
- 2022-09-02 Python?如何實時向文件寫入數據(附代碼)_python
- 2022-06-18 Go語言學習之時間函數使用詳解_Golang
- 2022-04-16 Android中RecyclerView實現簡單購物車功能_Android
- 2022-11-22 React?Context源碼實現原理詳解_React
- 2021-12-08 .net?core?api接口JWT方式認證Token_實用技巧
- 2023-02-23 Rust個人學習小結之Rust的循環_Rust語言
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支