1

When I use string formatting .format() inside a loop, I notice that the value is filled in with the first keyword in the list. I think the example below will clarify things what I meant.

I've tried with:

params = {
    'f': 'json',
    'where': "UPPER(ADDRESS) LIKE '%{}%' or UPPER(ADDRESS2) LIKE '%{}%'",
    'returnGeometry': 'true',
}

for keyword in ['A','B','C','D','E']:
    params['where'] = params['where'].format(keyword,keyword)
    print(params['where'])

Current output:

UPPER(ADDRESS) LIKE '%A%' or UPPER(ADDRESS2) LIKE '%A%'
UPPER(ADDRESS) LIKE '%A%' or UPPER(ADDRESS2) LIKE '%A%'
UPPER(ADDRESS) LIKE '%A%' or UPPER(ADDRESS2) LIKE '%A%'
UPPER(ADDRESS) LIKE '%A%' or UPPER(ADDRESS2) LIKE '%A%'
UPPER(ADDRESS) LIKE '%A%' or UPPER(ADDRESS2) LIKE '%A%'

Expected output:

UPPER(ADDRESS) LIKE '%A%' or UPPER(ADDRESS2) LIKE '%A%'
UPPER(ADDRESS) LIKE '%B%' or UPPER(ADDRESS2) LIKE '%B%'
UPPER(ADDRESS) LIKE '%C%' or UPPER(ADDRESS2) LIKE '%C%'
UPPER(ADDRESS) LIKE '%D%' or UPPER(ADDRESS2) LIKE '%D%'
UPPER(ADDRESS) LIKE '%E%' or UPPER(ADDRESS2) LIKE '%E%'

1 Answer 1

1

The first round of your loop (using keyword A) overwrites the where value in your dictionary so that the {} are no longer present when the next iteration of the loop (using keyword B) starts.

The solution is to keep a "clean" copy of the value and update it in each loop iteration:

where_string = "UPPER(ADDRESS) LIKE '%{}%' or UPPER(ADDRESS2) LIKE '%{}%'"

for keyword in ['A','B','C','D','E']:
    params['where'] = where_string.format(keyword,keyword)
    print(params['where'])

The output should be what you expect.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.