Python Creating a Function that checks if a part of a list is a number or not

I’m trying to create a function that takes a string with letters, numbers, and other characters, and then returns a string with only numbers and question marks in it. When I run the following function with the input arrb6???4xxbl5???eee5, it returns the whole string and not just numbers. What can I do to improve my code?

def questionmarkstry(string):
    list_string = [x for x in string]
    liststringnew = []
    for letter in list_string:
        if string == "1" or "2" or "3" or "4" or "5" or "6" or "7" or "8" or "9" or "0" or "?":
            liststringnew.append(letter)
        elif string != "1" or "2" or "3" or "4" or "5" or "6" or "7" or "8" or "9" or "0" or "?":
            pass
   return liststringnew

Here is an updated version:

def questionmarkstry(string):
    list_string = [x for x in string]
    liststringnew = []
    for l in list_string:
        if l == "1" or l == "2" or l == "3" or l == "4" or l == "5" or l == "6" or l == "7" or l == "8" or l == "9" or l == "0" or l =="?":
            liststringnew.append(l)
        else:
            pass
        
    return(liststringnew)

That’s not how you make an if statement with multiple clauses in Python (or any other language).

You want

if test_1 or test_2 or ... or test_11:
  ...

I edited my code to reflect those improvements, but it still gives back the whole string instead of just numbers and question marks.

Please post your most recent code, as the one in your first post is still not valid syntax.

Yeah, you didn’t make the change I suggested. "2" is not a logical conditional. string == "2" is.

I have now updated the code.

Why is there an elif? Wouldn’t an else with no conditionals work better?

Thanks for the help. I have now figured out the code.

1 Like