Last active
January 17, 2023 06:05
-
-
Save deangrant/dcbc49e8ae8930098f879f1d14b59d9e to your computer and use it in GitHub Desktop.
Mask a string by replacing a specific range of characters with asterisks (*)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def mask_string( | |
string: str, | |
end: int = 4 | |
) -> str: | |
""" | |
Mask a string by replacing all but the last number of characters with asterisks(*). | |
Parameters: | |
string (str): The string to be masked. | |
end (int): The number of characters to keep visible. | |
Returns: | |
str: The masked string. | |
Example: | |
original_string = "This is a test string." | |
masked_string = mask_string(original_string) | |
print(masked_string) | |
# '******************ing.' | |
""" | |
# Check if the value end is positive integer | |
if not isinstance(end, int) or end <= 0: | |
raise ValueError("end must be a positive integer") | |
# Mask all but the last characters | |
mask = '*' * (len(string) - end) | |
# Replace all but the last characters with the mask | |
return mask + string[-end:] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment