0

I have written a python script where I have collected some values in a list. I need to pass on these values to an URL in a loop where in each time a different value is picked up.
i..e, I want to achieve this:

http://www.abc.com/xyz/pqr/symbol=something[i].

Here "something" is a list and I have verified that it contains the proper values. However when I pass the values to the URL, I am not getting the desired results. I have tried with URL encoding for something[i] but still it is not giving me proper results. Can someone help me?

EDIT: My example script at the moment is:

import json
script=["Linux","Windows"]
for i in xrange(len(script)):
    site="abc.com/pqr/xyz/symbol=json.dumps(script[i])"; 
    print site 
beroe
  • 11,784
  • 5
  • 34
  • 79
Shunya
  • 2,785
  • 2
  • 18
  • 17
  • 1
    You might be able to accomplish what you want by using json. Convert `something[i]` to json and then you could have `/symbol=` – Red Cricket Mar 01 '14 at 06:08
  • 2
    Show us some code, some error messages, etc. – John Zwinck Mar 01 '14 at 06:11
  • http://stackoverflow.com/questions/4476373/simple-url-get-post-function-in-python does this help? – Nishant Shrivastava Mar 01 '14 at 06:18
  • Here is my example script: import json script=["Linux","Windows"] for i in xrange(len(script)): site="http://www.abc.com/pqr/xyz/symbol=json.dumps(script[i])" print site However, I am not getting the proper results. – Shunya Mar 01 '14 at 08:30

1 Answers1

1

I think the problem is your approach to formatting. You don't really need json if you have a list already and are just trying to modify a URL...

import json
script=["Linux","Windows"]
something = ["first","second"]
for i,j in zip(script,something):
    site="http:abc.com/pqr/xyz/symbol={0}".format(j)
    print i, site

This uses the .format() operator, which "sends" the values in parentheses into the string at the positions marked with {}. You could just add the strings together if it is always at the end. You could also use the older % operator instead. It does pretty much the same thing, but in this case it inserts the string j at the position marked by %s:

site="http:abc.com/pqr/xyz/symbol=%s" % (j)

Side note: I slightly prefer % because once you learn it, it can also be used in other programming languages, but .format() has more options and is the recommended way to do it since python 2.6.

Output:

Linux http:abc.com/pqr/xyz/symbol=first
Windows http:abc.com/pqr/xyz/symbol=second

You should be able to get close to what you want from this starting point, but if this is nothing like your desired output, then you need to clarify in your question...

Community
  • 1
  • 1
beroe
  • 11,784
  • 5
  • 34
  • 79
  • Perfect Solution, my script worked based on your answer. Thanks a ton. Could you please explain the formatting "symbol={0}.format(j)"?? – Shunya Mar 01 '14 at 10:41
  • OK, I added a bit of explanation, but check the docs for all the subtleties. – beroe Mar 01 '14 at 20:02