Nardi Braho
Nardi Braho

Reputation: 13

Add array elements one by one in a "for" loop?

I'm trying to add the array values one by one to an URL since each one is a different ID for an API call im trying to make.

The code works if I write the ID directly in the URL variable. But I have hundreds of API calls to make.

How can I print/add each array element one by one and the URL? Check the final output code and see how it adds the whole array instead of each element one by one.

import requests

ids = ["12ab", "13ab", "14ab"]

for x in ids:
  url = ("https://google.com/{}"+format(ids)+"?extraurlparameters")
  response = requests.request("DELETE", url)
  print(x)
  print(url)

print(response.text)

output

12ab
1
https://google.com/{}['12ab', '13ab', '14ab']?extraurlparameters
2
13ab
3
https://google.com/{}['12ab', '13ab', '14ab']?extraurlparameters
4
14ab
5
https://google.com/{}['12ab', '13ab', '14ab']?extraurlparameters
6

Upvotes: 1

Views: 172

Answers (4)

Trasha Dewan
Trasha Dewan

Reputation: 93

import requests
ids = ["12ab", "13ab", "14ab"]
for x in ids: 
    url = ("https://google.com/"+format(x)+"?extraurlparameters") 
    response = requests.request("DELETE", url) 
    print(x) 
    print(url)
    print(response.text)

change ids to x in line 4.

Upvotes: 1

will.mendil
will.mendil

Reputation: 1035

I think you misuse the format function:

import requests

ids = ["12ab", "13ab", "14ab"]

for id in ids:
  url = ("https://google.com/{}?extraurlparameters".format(id))
  response = requests.request("DELETE", url)
  print(id)
  print(url)

print(response.text)

Upvotes: 0

Christopher Peisert
Christopher Peisert

Reputation: 24194

Usually, format() is called at the end of the string.

url = "https://google.com/{}?extraurlparameters".format(x)

In Python 3.6+, you could use an f-string (format string), such as:

url = f"https://google.com/{x}?extraurlparameters"

Original code sample

import requests

ids = ["12ab", "13ab", "14ab"]

for x in ids:
  url = "https://google.com/{}?extraurlparameters".format(x)
  response = requests.request("DELETE", url)
  print(x)
  print(url)

print(response.text)

Upvotes: 0

LazyCoder
LazyCoder

Reputation: 1265

Replace your version with the following and let me know if it works

ids = ["12ab", "13ab", "14ab"]
for x in ids:
    url = ("https://google.com/{}".format(x)+"?extraurlparameters")
    print(url)

Upvotes: 2

Related Questions