← Back to list

How to Protect User Privacy with Data Masking in Python

When working with user data, protecting privacy is a critically important issue. Whether you are handling personal information, financial…

Gen. Devin DL. · 2025-12-28 09:20 · 1 claps · 3.1 min read
#python-data-masking #python-data-preprocessing
Open on Medium ↗
Wiki topics: ECO · Economy · General 🔒 · Cybersecurity

How to Protect User Privacy with Data Masking in Python

Photo by Christian Wiediger on Unsplash

Photo by Christian Wiediger on Unsplash

When working with user data, protecting privacy is a critically important issue. Whether you are handling personal information, financial data, or corporate data, sensitive details such as names, ID numbers, phone numbers, and email addresses must be properly safeguarded to prevent data leakage. In this post, We will share several practical data masking techniques and show how you can easily implement data protection using Python.

Phone Number Masking

Phone numbers are one of the most common types of sensitive information. A typical masking approach is to display only part of the number while replacing the middle digits with asterisks.

Below is a simple Python example that masks a U.S. phone number, keeping the first 3 digits (area code) and the last 4 digits visible.

def mask_phone(phone):
    if not phone or len(phone) != 10:
        return phone
    return phone[:3] + '*' * 3 + phone[-4:]

# Test example
phone = "4158675309"   # U.S. phone number
masked = mask_phone(phone)
print(masked)  # Output: 415***5309

Reminder: Before processing a phone number, remember to check its length to avoid errors caused by invalid input data.

ID Number Masking

ID numbers contain highly sensitive information. A common masking approach is to keep only the first 6 digits and the last 4 digits visible, while masking the remaining middle part.

In the example below, we assume a 9-character U.S. driver’s license ID. The function keeps the first 3 characters and the last 3 characters, replacing the middle part with asterisks.

def mask_driver_license(dl_id):
    if not dl_id or len(dl_id) != 9:
        return dl_id
    return dl_id[:3] + '*' * 3 + dl_id[-3:]

# Check the result
dl_id = "D12345678"   # U.S. Driver's License ID (example)
print(mask_driver_license(dl_id))  # Output: D12***678

Email Address Masking

Email address masking is slightly more complex because the part before the “@” symbol needs to be handled specially.

Below is a Python example that masks an email address by keeping only the first and last characters of the username and replacing the middle part with asterisks.

def mask_email(email):
    if '@' not in email:
        return email

    name, domain = email.split('@')

    if len(name) <= 2:
        masked_name = '*' * len(name)
    else:
        masked_name = name[0] + '*' * (len(name) - 2) + name[-1]

    return f"{masked_name}@{domain}"

# Test example
email = "joe.sanjuan@company.com"
print(mask_email(email))  # Output: j********n@company.com

Credit Card Number Masking

Credit card numbers are highly sensitive information. A common masking approach is to display only the last 4 digits and replace all preceding digits with asterisks.

Below is a Python example using a VISA card number sample (VISA cards typically start with 4 and have 16 digits).

def mask_credit_card(card_num):
    if not card_num:
        return card_num
    return '*' * (len(card_num) - 4) + card_num[-4:]

# Test example (VISA card number)
card = "4111111111111234"
print(mask_credit_card(card))  # Output: ************1234

Batch Processing Masking

Sometimes we need to process a large amount of data. In such cases, we can use a dictionary to batch-handle different types of sensitive information.

def batch_mask_data(data):
    masks = {
        'phone': mask_phone,
        'driver_license': mask_driver_license,
        'email': mask_email,
        'credit_card': mask_credit_card
    }

    for key, value in data.items():
        if key in masks:
            data[key] = masks[key](value)

    return data

# Test data (U.S. user sample)
user_data = {
    'name': 'John Smith',
    'phone': '4158675309',
    'email': 'john.smith@example.com',
    'driver_license': 'D12345678',
    'credit_card': '4111111111111234'
}

masked_data = batch_mask_data(user_data)
print(masked_data)

When writing code, always remember to consider data validation and exception handling. Although masked data no longer reveals the original details, it is still important to ensure data integrity and usability. In real-world projects, it is recommended to encapsulate these masking methods into a utility class for easier reuse and maintenance.

After finishing the code, make sure to test various edge cases, such as null values and incorrectly formatted data. Data security is never a small matter — being extra cautious is always a good practice.

Conclusion

In this post, we explored practical and reusable ways to protect user privacy through data masking in Python. By masking common sensitive fields such as phone numbers, email addresses, driver’s license IDs, and credit card numbers, we demonstrated how to reduce the exposure of personal information while preserving data integrity and usability.

We also showed how to apply these techniques in batch processing using a dictionary-based approach, making the solution scalable and easy to extend. With proper data validation, exception handling, and thorough testing of edge cases, data masking can become a reliable part of any production system.

Ultimately, incorporating data masking into your data processing pipeline is not just a technical improvement — it is a best practice that helps build safer, more trustworthy applications.


메타데이터
post_id
a054cd56a58d
slug
how-to-protect-user-privacy-with-data-masking-in-python-a054cd56a58d
url
https://medium.com/@tubelwj/how-to-protect-user-privacy-with-data-masking-in-python-a054cd56a58d
canonical_url
https://medium.com/@tubelwj/how-to-protect-user-privacy-with-data-masking-in-python-a054cd56a58d
author_url
https://medium.com/@tubelwj
status
ok
fetched_at
2026-06-17 08:20:12