Home > Back-end >  Why I can't delete everything except for certain characters using a loop
Why I can't delete everything except for certain characters using a loop

Time:01-29

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:

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

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

CodePudding user response:

Try this:

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

CodePudding user response:

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"))
  •  Tags:  
  • Related