user10386194
user10386194

Reputation:

Masking part of a string

So my question is, I have an assignment that needs to be solved.

I have a simple function:

def multiplicator(x, y):
    var1 = x * y
    return var1

I need to use this multiplicator to get this result in another function:

Enter: "5435843398429829"     output: "****************9829"

The last 4 digits in the input should not be masked, but the rest should be masked with a "#".

Upvotes: 4

Views: 21683

Answers (3)

monkut
monkut

Reputation: 43860

just implemented this, so I thought I'd drop this here:

For Python >= 3.6 (uses f-strings)

from math import ceil

def mask_string(s, perc=0.6):
    mask_chars = ceil(len(s) * perc)
    return f'{"*" * mask_chars}{s[mask_chars:]}'

Upvotes: 4

jkhadka
jkhadka

Reputation: 2543

Good solution by Vengat, and this also works with rjust.

def multiplicator(x, y):
    var1 = str(x * y)
    #################
    # masking
    #################
    masked = var1[-4:].rjust(len(var1),"#")
    return masked

Without masking in function

def multiplicator(x, y):
    return x * y


def masker(n):
    var1 = str(n)
    masked = var1[-4:].rjust(len(var1),"#")
    return masked

Upvotes: 0

Prometheus
Prometheus

Reputation: 618

Let us store that number you want to mask in a variable called masked.

unmasked = str(unmasked)
masked = len(unmasked[:-4])*"#"+unmasked[-4:]

I hope this works.

Upvotes: 14

Related Questions