Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how do I make a function where i have three str values and based on the third str it prints the letters of str1 and str2?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading