Skip to content

Instantly share code, notes, and snippets.

@deangrant
Last active January 17, 2023 06:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save deangrant/dcbc49e8ae8930098f879f1d14b59d9e to your computer and use it in GitHub Desktop.
Save deangrant/dcbc49e8ae8930098f879f1d14b59d9e to your computer and use it in GitHub Desktop.
Mask a string by replacing a specific range of characters with asterisks (*)
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