SoFunction
Updated on 2024-11-10

Python Write an increment function for the numeric suffix part of a string

Demand:

Python handles renamed strings, adding or incrementing numeric string suffixes

  • For 2 renamed strings, add a numeric suffix, such as two duplicate stringss1 = “name”, s2 = “name”, set the name of s2 toname_1
  • Corresponding to 3 or more renamed strings, the numeric part is realized incrementally, initiallys1=s2=s3=“name", renamed to gets1=“name”,s2=“name_1”, s3=“name_2

To handle strings flexibly, it is most convenient to use the re module. Here is a way to increment a string with an underscore + a number as a suffix.

def increase_string_suffix(s, incr_num=1):
    """
    With numerical suffix "_d"The string self-increment method of "name_1" Add 1 --> "name_2"
    Example
    -----------------
    >>> s = "name_01"
    >>> increase_string_suffix(s, incr_num=2)
    'name_03'
    """
    suffix_searched = (r"(_)(\d+)$", s)
    if suffix_searched:
        suffix_plus_1 = (
            r"(_)(\d+)$",
            lambda x: f"{(1)}{str(int((2)) + incr_num).zfill(len((2)))}",
            s
        )
    else:
        suffix_plus_1 = f"{s}_1"
    return suffix_plus_1

The example can be run directly in the code in the doc section of the comments, the parameter s is the string to be passed in, and incr_num is the number of steps to be incremented at a time
The core part of the code is the method, r"(_)(\d+)$" is to match the search part, () to match the part of the group, (1) is () matched to the "", (2) is matched to the number of parts, zfill to the left to fill in the length of the 0 fill in the length of the, for example, 01 → 02 and not 01 → 2

It is also possible to write a decreasing, or modifying, prefixed

Example:

def increase_string_prefix(s, incr_num=1):
    """
    With numeric prefix "d-"The string self-increment method of "1-name" Add 1 --> "2-name"
    Example
    -----------------
    >>> s = "1-name"
    >>> increase_string_prefix(s, incr_num=1)
    '2-name'
    """
    prefix_searched = (r"^(\d+)(-)", s)
    if prefix_searched:
        prefix_plus_1 = (
            r"^(\d+)(-)",
            lambda x: f"{str(int(()[0]) + incr_num).zfill(len(()[0]))}{()[1]}",
            s
        )
    else:
        prefix_plus_1 = f"1-{s}"
    return prefix_plus_1

For more on how to use regular expressions, see the previousthis article

to this article on Python to write a string digital suffix part of the incremental function of the article is introduced to this, more related Python incremental function content please search for my previous articles or continue to browse the following related articles I hope you will support me in the future more!