I am trying to replace the entire string with '#' except the last 4 characters.
The following:
def maskify(cc):
c2 = cc.replace(cc[:-4], '#')
return c2
print(maskify('TestName'))
Results in:
#Name
I want it to return:
####Name
What am I doing wrong here? Thanks
2 Answers 2
For a simpler solution you could instead use rjust on the last 4 characters of the string, and fill it with # up to its original length:
s = 'TestName'
s[-4:].rjust(len(s), '#')
'####Name'
The problem with your function, is that you have to repeat the elements you want to use to replace as many times as replacements there will be. So you should do:
def maskify(cc):
c2 = cc.replace(cc[:-4], '#'*len(cc[:-4]))
return c2
Comments
yatu's solution using rjust() looks good, but str.replace() is a false friend. It works for a reasonably varied string, but if elements are repeated in the string it can fail (this is yatu's 2nd solution):
def maskify(cc):
c2 = cc.replace(cc[:-4], '#'*len(cc[:-4]))
return c2
print(maskify('12121212'))
gives,
########
I suggest 'building' the new string like this instead,
def maskify(cc):
mask = '#' * (len(cc)-4)
return mask+cc[-4:]
which gives the desired result,
####1212