zihan meng zihan meng - 3 months ago 10
Python Question

how to use for loop to iterating url index to collect the data

I am a newbie in python. I want to write a for loop to iterate the index in order to pull the data.

Here is my code:

url90=[]
for i in range(-90,0):
url90.append('http://staging.foglogic.com/api/v1/index.php/accounts/34/reports/bcjobs?cmd=json&datestr=today&**index=i**&filter={}&filterOverride=0&su=1')


I want index=i which from range(-90,0), however the python consider my i as a string instead of a integer.

my result give me 90 identical url :

'http://staging.foglogic.com/api/v1/index.php/accounts/34/reports/bcjobs?cmd=json&datestr=today&index=i&filter={}&filterOverride=0&su=1'


Is there anyone can help me to solve the problem?

Thank you!

Answer

If you think that i variable will automatically be used in the string used to populate the list, you are wrong. It does not work that way. Use .format:

url90=[]
for i in range(-90,0):
    url90.append('http://staging.foglogic.com/api/v1/index.php/accounts/34/reports/bcjobs?cmd=json&datestr=today&index={0}&filter={{}}&filterOverride=0&su=1'.format(i))
print("\n".join(url90))

See Python demo

Note that literal { and } in the format string must be doubled (see index={0}). The {0} is a placeholder for the i variable (see filter={{}}) that is the first and only argument to the method.