Home > database >  how do I make a function where i have three str values and based on the third str it prints the lett
how do I make a function where i have three str values and based on the third str it prints the lett

Time:11-13

If I have a function:

def chars(str1: str, str2: str, str3: str) -> str:

What should I put inside this so that it returns a new string where the character at index i is str1[i] if str3[i] is 0 and str2[i] if str3[i] is 1.

for example, if I had:

chars('dog', 'cat', '001')

it would output:

dot #since the first 0 is d from str1, the second 0 is o from str1 and the 1 is t from str2

Another example could be:

chars('army', 'game', '0011')

it would output:

arme ##since the first 0 is a from str1, the second 0 is r from str1, the first 1 is m from str2 and the second 1 is e from str2

This is what I tried so far:

for i in range(len(str3)):
    if str3[i] == '0':
        return str1[i]
    else:
        return str2[i]

but it only returns the first letter and nothing else so how would I fix this?

CodePudding user response:

The code can be fixed by adding a variable

def chars(str1: str, str2: str, str3: str) -> str:
    final = "" # I added a variable with name final
    for i in range(len(str3)):
        if str3[i] == '0':
            final  = str1[i]
        else:
            final  = str2[i]
    return final
    
print(chars("dog", "cat", "001")) # For testing purpose

Here the code goes as follows final = ""

  1. str3[0] = 0 so final = final str1[0] -> final = "d"
  2. str3[1] = 0 so final = final str1[1] -> final = "do"
  3. str3[2] = 1 so final = final str2[2] -> final = "dot" return final -> "dot"

CodePudding user response:

I think following function does the expected output, try it and let's know:

def chars(str1: str, str2: str, str3: str) -> str:
    out=str1[:(len(str1)-1)]
    out =str2[-1:]
    out=''.join(out)
    
    return out
  • Related