2

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

asked Feb 2, 2019 at 21:16

2 Answers 2

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
answered Feb 2, 2019 at 21:18
Sign up to request clarification or add additional context in comments.

Comments

1

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
answered Jul 19, 2020 at 12:47

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.