Questions about replacing a string of banned words with substitutes with a given sentence using for loop

  python, string

This is the question:

Implement a function called mask_out in q3.py.
• The mask_out function takes in three parameter:
o sentence (type: str)
o banned (type: str)
o substitutes (type: str)
• This function returns a string that is a copy of sentence, except that if a character in sentence is found in
banned, this character will be replaced with a corresponding character in substitutes whose index in
substitutes is the same as the index of the banned character in the parameter banned.
For example, if banned is ‘abc’ and substitutes is ‘xyz’, then every ‘a’ in sentence is replaced with
‘x’, every ‘b’ is replaced with ‘y’, and every ‘c’ is replaced with ‘z’.
• You can assume the following:
o banned contains unique characters, i.e., there are no duplicated characters in banned.
o substitutes contains at least one character.
o banned is either of the same length as substitutes or longer than substitutes. When banned
is longer than substitutes, the additional characters in banned will be replaced with the first
character in substitutes. For example, if banned is ‘abcde’ and substitutes is ‘xy’, then ‘c’,
‘d’ and ‘e’ will be replaced by ‘x’.

and my code is as follows:

def mask_out(sentence, banned, substitutes):

store=""

if len(banned)==len(substitutes):
    for ch in sentence:
        if ch in banned:
            for i in range(0,len(banned)):

                if banned[i]==ch:
                    store=store+substitutes[i]
        if ch not in banned:
            store=store+ch
return store
if len(banned)>len(substitutes):
     for ch in sentence:
        if ch in banned:
            for i in range(0,len(banned)):
                if i<=len(substitute):

                    if banned[i]==ch:
                        store=store+substitutes[i]
                if i>len(substitute):
                    store=store+substitutes[0]
                    
        if ch not in banned:
            store=store+ch
            
return store

These are the test given:

print(‘Test 1’)

print(‘Expected:abcd#’)

print(‘Actual :’ + mask_out(‘abcde’, ‘e’, ‘#’))
print()

print(‘Test 2’)

print(‘Expected:#$solute’)

print(‘Actual :’ + mask_out(‘absolute’, ‘ab’, ‘#$’))

print()

print(‘Test 3’)

print(‘Expected:121hon’)

print(‘Actual :’ + mask_out(‘python’, ‘pyt’, ’12’))

print()

I’ve got the answer for test 1 and 2 but there were no output regarding test 3(it is probably due to error in my second if) and i have no idea why. I am really new to python and i tried changing the second to elif there is a syntax error. Please help me thank you.

Source: Python Questions

LEAVE A COMMENT