Censor Credit Card Numbers
Intermediate · Write the code · from Python Regular Expressions: Pattern Matching from Basics to Advanced
From the lesson: Python Regular Expressions: Pattern Matching from Basics to Advanced
Imagine you're working at a help desk and need to find every email address buried in thousands of support tickets. You could scan each line character by character, but that would take forever. Regular expressions let you describe the pattern of an email address, and Python finds every match for you.
Read the lessonWrite a function censor_cards(text) that replaces all sequences of 4 groups of 4 digits separated by dashes (like 1234-5678-9012-3456) with ****-****-****-XXXX, where XXXX is the last 4 digits. Use re.sub() with a function or groups.
import re
def censor_cards(text):
# Replace card numbers, keeping only last 4 digits
pass
print(censor_cards('Card: 1234-5678-9012-3456 and 9999-8888-7777-6666'))
More Regex exercises
- Find a Phone NumberIntermediate
- Extract All HashtagsIntermediate
- Predict the Regex OutputIntermediate
- Fix the Email ValidatorIntermediate
- Parse a Log EntryIntermediate
- Clean and Normalize WhitespaceAdvanced
All Python exercises · 50 practice problems · Standard Library Essentials quiz