可以通過字符串的切片方法和字符串替換方法來實現對電子郵箱進行脫敏操作。
具體實現過程如下:
1. 使用字符串的切片方法獲取電子郵箱中@前的字符和@后的字符,分別保存到變量中。
2. 對@前的字符進行處理,將除前3位以外的其他字符都替換成*,然后將處理后的字符和@符號拼接起來。
3. 對@后的字符進行處理,找到第一個點(.)的位置,將該點前的字符替換成*,然后將處理后的字符和點以及點后的字符拼接起來。
4. 將處理后的@前字符和@后字符以及@符號拼接起來,即為脫敏后的電子郵箱。
下面是實現代碼示例:
email = "candy@example.com"
at_position = email.index("@") # 獲取@符號位置
# 獲取@前的字符和@后的字符
prefix = email[:at_position]
suffix = email[at_position+1:]
# 對@前的字符進行脫敏處理
masked_prefix = prefix[:3] + "*" * (len(prefix) - 3)
# 對@后的字符進行脫敏處理
dot_position = suffix.index(".")
masked_suffix = "*" * dot_position + suffix[dot_position:]
# 將處理后的字符拼接起來
masked_email = masked_prefix + "@" + masked_suffix
print(masked_email) # 輸出:can***@ex*****.com