Is there a better way to mask a credit card number in python?

So, I have a csv file that contains full credit card numbers. We do not need the full number, so I am writing a quick script to parse through csv and replace the cc number with a masked view. (all * except the last four). I am new to python and hacked this and it works, but to find out if I want to know if this can be done easier.

Suppose str is the full credit card number. But for the sake of my example, I just use the string "CREDITCARDNUMBER".

str = "CREDITCARDNUMBER"; strlength = len(str) masked = strlength - 4 slimstr = str[masked:] print "*" * masked + slimstr 

The result is exactly what I want

 ************MBER 

But I'm sure there is a more elegant solution. :) Thank you!

+6
source share
6 answers

Niter yet:

 >>> s = "CREDITCARDNUMBER" >>> s[-4:].rjust(len(s), "*") '************MBER' 
+13
source

Perhaps a little more elegant:

 card = "CREDITCARDNUMBER" print "*" * (len(card) - 4) + card[-4:] 

Note that I avoided using the name str because this is already the name of an inline string type. It is generally not recommended to use names that obscure embedded names.

+6
source

With Format String and Slicings :

 '{:*>16}'.format(card[-4:]) 
+2
source

For those who want to keep the Issuer's Identification Number (formerly referred to as โ€œBank Identification Numberโ€ (BIN)), which is usually the first 6 digits that should do the job:

 print card[:6] + 'X' * 6 + card[-4:] '455694XXXXXX6539' 
+1
source

You can make it a little shorter, for example:

 str = "CREDITCARDNUMBER"; print "*" * (len(str) - 4) + str[-4:]; 
0
source

I need a flexible way to mask the material, so I decided to share ...

 def mask(string, start=0, end=0, chunk=4, char="*"): if isinstance(string, str): string_len = len(string) if string_len < 3: return "input len = {}, what the point?".format(string_len) if start <= 0 or end <= 0: start = string_len // chunk end = start if string_len <= 4: mask_len = string_len // 2 start = 1 if mask_len - 1 == 0 else mask_len - 1 end = start else: mask_len = string_len - abs(start) - abs(end) return string[:abs(start)] + (char * mask_len) + string[-end:] if __name__ == "__main__": s = "abcdefghijklmnopqrstuvwxyz01234567890a0b0c0d0e0f1a1b1c1d1e1f2a2b" l = [i for i in s] message = "ip: {}\nop: {}\n" section = "-"*79 print("\nSTRINGS") print(section) print(message.format(s[:4], mask(s[:4]))) print(message.format(s[:3], mask(s[:3]))) print(message.format(s[:2], mask(s[:2]))) print(message.format(s, mask(s))) print(message.format(s, mask(s,start=2,end=4,char="#"))) print(message.format(s, mask(s,start=3,end=3,char="x"))) 
0
source

Source: https://habr.com/ru/post/910861/


All Articles