Home > Net >  Unable to fix an issue that occurs while using string format inside a loop
Unable to fix an issue that occurs while using string format inside a loop

Time:07-25

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%'

CodePudding user response:

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.

  • Related