Home > database >  Credit Card Number Sensor Challenge
Credit Card Number Sensor Challenge

Time:09-03

So I am trying to write a program that sensors the first 12 digits of a 'credit card number' and then prints it with the last 4 digits still there. (4444444444444444=************4444). I am having a problem making the loop stop at just the first 12 digits. The output is always 12 *'s. Here is the code:

credit=""
while len(credit)<16 or len(credit)>16:
        credit=input("Please input credit card number: ")
x=1
k="*"
while x<12:
    for ele in credit:
        if ele.isdigit() and x<12:
            credit=credit.replace(ele, k)
            x=x 1
print(credit)

CodePudding user response:

Without the re module you could this.

First of all ensure that the input is exactly 16 characters and is comprised entirely of digits.

Then print 12 asterisks (constant) followed by the last 4 characters of the input which can be achieved with traditional slicing.

while len(ccn := input('Please input credit card number: ')) != 16 or not ccn.isdigit():
    print('Must be 16 digits. Try again')

print('*'*12, ccn[-4:], sep='')

CodePudding user response:

import re
print(re.sub('\d{12}', '*'*12, credit))
  • Related