给敏感字符串进行替换中间部分,从而达到脱敏的效果。代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| def HideMid(str1, count: int, fix='*'): """ #隐藏/脱敏 中间几位 str 字符串 count 隐藏位数 fix 替换符号 """ if not str1: return '' count = int(count) str_len = len(str1) ret_str = '' if str_len == 1: return str1 elif str_len == 2: ret_str = str1[0] + '*' elif count == 1: mid_pos = int(str_len / 2) ret_str = str1[:mid_pos] + fix + str1[mid_pos + 1:] else: if str_len - 2 > count: if count % 2 == 0: if str_len % 2 == 0: ret_str = str1[:int(str_len / 2 - count / 2)] + \ count * fix + str1[int(str_len / 2 + count / 2):] else: ret_str = str1[:int((str_len + 1) / 2 - count / 2)] + count * fix + str1[int(( str_len + 1) / 2 + count / 2):] else: if str_len % 2 == 0: ret_str = str1[:int(str_len / 2 - (count - 1) / 2)] + count * fix + str1[int(str_len / 2 + ( count + 1) / 2):] else: ret_str = str1[:int((str_len + 1) / 2 - (count + 1) / 2)] + count * fix + str1[ int((str_len + 1) / 2 + ( count - 1) / 2):] else: ret_str = str1[0] + fix * (str_len - 2) + str1[-1]
return ret_str
|