0

If I want to write a function mask(a, b) that takes two strings, a and b, and change the letters to * in a in the order they appear in b, returned in a new string.

For example if s1="How are you doing today" and s2="hardod" than the new string/updated s1 string should be "*ow **e you **ing to*ay".

Is there any way to do this?

def mask(a,b):
    for ch in s2:
    
         s1 = s1.replace(ch, '*', 1)
    return s1

print(mask("How are you doing today", "hardod"))

Then I get the output H*ll*, *ow **e you Anders? which is wrong as they should be replaced in turn, ie the first letter in b should replace the same letter in a on the first index it appears on and no more, then b should continue to the second letter ib and replace the same letter ia on the first index on which it appears and no more etc.

  • hello, please show us your attempt. At leat, you can walk on a string with a for loop and compare each letter in s1 to s2 then it is the same , replace letter by '*' – DonKnacki Apr 21 '21 at 11:13
  • here is a question that can help you- https://stackoverflow.com/questions/3411771/best-way-to-replace-multiple-characters-in-a-string – Prathamesh Apr 21 '21 at 11:16
  • is it case sensitive? – Vikash Kumar Apr 21 '21 at 11:18
  • @DonKnacki I have now posted my attempt, thank you! – user15415514 Apr 21 '21 at 11:20
  • @user15415514 : good. Two problems : you should not use s1 and s2 in your function but a and b . About the first letter, as said by @vikash kumar, if you want to not take care about case, you can apply `lower()` to your sting – DonKnacki Apr 21 '21 at 11:25

2 Answers2

2

I would have done something like this :

def mask(a, b):
    start_index = 0
    for c in b:
        for i in range(start_index, len(a)):
            if c == a[i]:
                a = "".join((a[:i], "*", a[i+1:]))
                start_index = i+1
                break
    return a

Your choice to make it case sensitive or not.

tronconux
  • 36
  • 2
  • And if I want to make in insensitive, where do I put `.lower()`? I tried with `if c.lower() == a[I].lower()` but with no success. – user15415514 Apr 21 '21 at 11:41
  • What you did works for me. But you could just set a and b to lowercase at the start of the function. – tronconux Apr 21 '21 at 13:28
0
def replace(s, position, character):
    return s[:position] + character + s[position+1:]

def mask(a,b):
    indexb=0
    for indexa in range(0,len(a)):
         ch=a[indexa]
         if (ch.lower()==b[indexb]):
            a=replace(a,indexa,'*')
            indexb=indexb+1
            if (indexb==len(b)):
                indexb=0
    return a

print(mask("How are you doing today", "hardod"))

gives

*ow **e you **ing to*ay
Alex Fleischer
  • 9,276
  • 2
  • 12
  • 15