简体   繁体   中英

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:

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

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

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"))

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"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM