Skip to content

Instantly share code, notes, and snippets.

@wcDogg
Last active January 21, 2023 06:15
Show Gist options
  • Save wcDogg/2ac9d388a13f4b1b2dad759c2219e906 to your computer and use it in GitHub Desktop.
Save wcDogg/2ac9d388a13f4b1b2dad759c2219e906 to your computer and use it in GitHub Desktop.
A function to replace some or all of a string's characters with asterisks.

Python: Obfuscate String

A function to replace some or all of a string's characters with *** asterisks.

def obfu_string(string: str, show_first: bool = True, show_last: bool = True) -> str:
  '''Obfuscates a string by replacing characters with *asterisks.
  '''

  str_list_in: list = []
  str_list_in.extend(string)
  str_len: int = len(str_list_in)
  str_list_out: list = [] 
  bound_lower: int = None
  bound_upper: int = None

  if show_first:
    bound_lower = 3
  else:
    bound_lower = 0

  if show_last:
    bound_upper = str_len - 1
  else:
    bound_upper = str_len

  for char in range(str_len):
    if char in range(bound_lower, bound_upper): 
      str_list_out.append('*')
      continue
    # else
    str_list_out.append(str_list_in[char])
     
  return ''.join(str_list_out)


# Test
if __name__ == "__main__":

  username = 'hello@domain.com'
  password = '}7Daq9M(R,LGla}]AHM8'

  print(obfu_string(username, True, True))     # hel************m
  print(obfu_string(password, False, False))   # ******************** 
  print(obfu_string(username, True, False))    # hel*************
  print(obfu_string(username, False, True))    # ***************m
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment