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.

Easy Python 3.9+ Aug 9, 2026 Strings & text 13 views 0 copies

Python code

9 lines
Python 3.9+
import 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

stdout
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

  1. Use re.sub with a lambda and a character class to allow spaces or hyphens between groups.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Strings & text

Related tutorials and quizzes for this topic.