REGEX_dynamic substitution using function

Viewed 28
1 Answers

Here is the function with comments:

def hide_reserve_3(s):
    return '*' * (len(s[0])-3) + s[0][-3:]
    #       ^ repeat * length        ^ slice for last 3 characters
    #         of string - 3

So this function builds an output consisting of a string with * repeated the length of the input s minus 3, concatenated with the final 3 digits in s.

The outer call to re.sub will match every number substring in the input and replace it by using the above slicing function.

Related