How to use Python to write an incremental function of the numeric suffix of a string
This article introduces the knowledge of "how to use Python to write an incremental function of a string number suffix". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
Demand:
Python handles duplicate name strings, adding or incrementing numeric string suffixes
For 2 duplicate strings, add a numeric suffix, such as two duplicate strings S1 = "name", S2 = "name", and set the name of S2 to name_1
Corresponding to 3 or more strings with duplicate names, the number is incremented. At the beginning, S1 = "name" is renamed to get S1 = "name", S2 = "name_1", S3 = "name_2".
To deal with string problems flexibly, it is most convenient to use re module.
Here is a way to increment a suffix string with an underscore + number
Def increase_string_suffix (s, incr_num=1):
"
String self-increment method with numeric suffix "_ d", "name_1" self-increment 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
The example can run the doc part of the comment directly in the code, the parameter s is the string to be passed in, and incr_num is the number of steps to be increased at a time
The core part of the code is the re.sub method, r "(_) (\ d +) $" is the matching search part, () the matching part is grouped, x.group (1) is () matched to "", x.group (2) is the matching number part, and zfill fills 0 to the left to fill in the length, for example 01 → 02 instead of 01 → 2.
You can also write a descending, or modify the prefix, for example
Def increase_string_prefix (s, incr_num=1):
"
String self-increment method with numeric prefix "d -", "1-name" self-increment 1-- > "2-name"
Example
-
> s = "1-name"
> increase_string_prefix (s, incr_num=1)
'2murame`
"
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
This is the end of the content of "how to write an incremental function of a string with a numeric suffix in Python". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!