Geeks of Coding

Join us on Telegram

Viewing 0 reply threads
  • Author
    • #1067
      Abhishek TyagiAbhishek Tyagi

      Qwiklab Assessment: Working with Regular Expressions
      It’s time to put your new skills to the test! In this lab, you’ll have to find the users using an old email domain in a big list using regular expressions.
      What you’ll do
      Replacing the old domain name ( with a new domain name (
      Storing all domain names, including the updated ones, in a new file.

      #!/usr/bin/env python3
      import re
      import csv
      def contains_domain(address, domain):
        """Returns True if the email address contains the given,domain,in the domain position, false if not."""
        domain = r'[\w\.-]+@'+domain+'$'
        if re.match(domain,address):
          return True
        return False
      def replace_domain(address, old_domain, new_domain):
        """Replaces the old domain with the new domain in the received address."""
        old_domain_pattern = r'' + old_domain + '$'
        address = re.sub(old_domain_pattern, new_domain, address)
        return address
      def main():
        """Processes the list of emails, replacing any instances of the old domain with the new domain."""
        old_domain, new_domain = '', ''
        csv_file_location = '<csv_file_location>'
        report_file = '<path_to_home_directory>' + '/updated_user_emails.csv'
        user_email_list = []
        old_domain_email_list = []
        new_domain_email_list = []
        with open(csv_file_location, 'r') as f:
          user_data_list = list(csv.reader(f))
          user_email_list = [data[1].strip() for data in user_data_list[1:]]
          for email_address in user_email_list:
            if contains_domain(email_address, old_domain):
              replaced_email = replace_domain(email_address,old_domain,new_domain)
          email_key = ' ' + 'Email Address'
          email_index = user_data_list[0].index(email_key)
          for user in user_data_list[1:]:
            for old_domain, new_domain in zip(old_domain_email_list, new_domain_email_list):
              if user[email_index] == ' ' + old_domain:
                user[email_index] = ' ' + new_domain
        with open(report_file, 'w+') as output_file:
          writer = csv.writer(output_file)
Viewing 0 reply threads
  • You must be logged in to reply to this topic.