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

Why I can't delete everything except for certain characters using a loop

I have a code

def printer_error(s):
    allowed = "abcdefghijklm"
    return [s.replace(x, "") for x in allowed if x in s]
print(printer_error("xyzabcdef"))

That is what code must returns:

"abcdef"

And that is what code returns really:

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

['xyzbcdef', 'xyzacdef', 'xyzabdef', 'xyzabcef', 'xyzabcdf', 'xyzabcde']

I think that the problem is on line 3, but idk what`s wrong

>Solution :

Its because you’re using a list comprehension, instead you just have to have that replace function, like this…

def printer_error(s):
    allowed = "abcdefghijklm"

    for char in s:
        if char not in allowed:
            s = s.replace(char, "")

    return s
print(printer_error("xyzabcdef"))
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