Python Practice › RegEx Programs › Program 14
Mask card numbers
Write a Python program to mask all but the last 4 digits of card numbers.
Output
Card XXXX-XXXX-XXXX-1234 and XXXX-XXXX-XXXX-9876
Approach
- Capture the last 4 digits and replace the rest.
Solution
import re text = "Card 4111 1111 1111 1234 and 5500-0000-0000-9876"print(re.sub(r"\d{4}[ -]\d{4}[ -]\d{4}[ -](\d{4})", r"XXXX-XXXX-XXXX-\1", text))Output
Card XXXX-XXXX-XXXX-1234 and XXXX-XXXX-XXXX-9876
Learn the concept
New to this topic? Read the lesson, then come back.