How to Mask Credit Card Middle Digits in Python
Mask the middle digits of credit card numbers in a string, keeping only the first 8 and last 4 digits, using regular expressions.
Python code
9 linesimport re
def mask_credit_card(text: str) -> str:
pattern = re.compile(r'(\d{4}[-\s]?)(\d{4}[-\s]?)(\d{4}[-\s]?)(\d{4})')
return pattern.sub(lambda m: m.group(1) + m.group(2) + '****' + m.group(4), text)
if __name__ == "__main__":
sample = "Card: 1234-5678-9012-3456 and 1111 2222 3333 4444"
print(mask_credit_card(sample))
Output
Card: 1234-5678-****-3456 and 1111 2222 **** 4444
How it works
The regular expression captures four groups of four digits, separated by optional hyphens or spaces. The substitution function re-forms the string with the first two groups intact, replaces the third group with asterisks, and appends the last group. This preserves the original separator style (hyphen or space) before the masked group. The pattern assumes standard 16-digit card numbers commonly used in real-world data.
Common mistakes
- Using a regex that doesn't account for optional separators, so it fails on formatted numbers.
- Replacing the entire number instead of just the middle digits, exposing too little data.
- Forgetting to use a raw string for the pattern, causing escape sequence issues.
- Assuming all card numbers have exactly 16 digits without handling variations.
Variations
- Use re.sub with a lambda and a character class to allow spaces or hyphens between groups.
- Implement a non-regex approach by splitting on separators and joining with the masked middle part.
Real-world use cases
- Logging credit card numbers in a sanitized format to comply with PCI DSS requirements.
- Displaying a masked card number in a customer portal for verification without exposing full details.
- Redacting card numbers in support tickets or chat transcripts before storing them in a database.
Sponsored
More from Strings & text
- Automatically Detect Weak Passwords from Large Password Lists in Python easy
- Build CSV row from Python list with proper quoting easy
- Build a Secure Password Strength Checker in Python easy
- Convert Natural Language Dates to Datetime in Python medium
- Count Characters, Words, and Lines in Python Text easy
- Extract Data from Strings in Python: Beginner's Guide easy
Keep learning
Related tutorials and quizzes for this topic.