Search code examples
pythonlistfor-loopuser-inputstring-parsing

How do I find if anything in a list is in a string and determine what that "anything" is?


I have a need to read from a user input and parse it into 3 parts, the first piece is the row value, the second is the condition (==, !=, > etc.) and the third is the compare-value. User input: 0=="6/1/2014 0:00:00" --> Therefore, row would be 0, condition would be "==" and compare-value would be "6/1/2014 0:00:00"

Here is what I have:

    promptList = ["0 == 6/12/16 00:00:00", "1 > 47.20"]
    for prompt in promptList:
    if any(comparator in prompt for comparator in comparatorsList):
        prompt = prompt.split(comparator)
        row = prompt[0].strip()
        condition = prompt[1].strip()
        comparator = str(comparator).strip()
        print(row, comparator, condition) #test to see print statement, not needed

However, it says that I do not have comparator defined. I need comparator to know what to split the string by because you never know where the comparator would show up (i.e: 0 == 0 VS. 20124 > 6/2/12 00:32:10)

How do I set my 3 variables!


Solution

  • The variable comparator is scoped within your generator comprehension and won't exist outside of it. Instead of using the any construct, which is throwing away valuable information here, namely which comparator actually is contained, you could just expand it out into a for loop instead:

    comparatorsList = set(["==", "!=", ">", ">=", "<=", "<"])
    promptList = ["0 == 6/12/16 00:00:00", "1 > 47.20"]
    
    for prompt in promptList:
        for comparator in comparatorsList:
            if comparator in prompt:
                prompt = prompt.split(comparator)
                row = prompt[0].strip()
                condition = prompt[1].strip()
                comparator = str(comparator).strip()
                print(row, comparator, condition) 
                break
    

    Prints:

    ('0', '==', '6/12/16 00:00:00')
    ('1', '>', '47.20')