我试图将数组值一个一个地添加到URL,因为每个值都是我要进行的API调用的不同ID。
如果我直接在URL变量中写入ID,则代码有效。但是我要进行数百次API调用。
我如何一一打印/添加每个数组元素和URL?检查最终的输出代码,看看如何将整个数组而不是每个元素一个接一个地添加。
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)
输出
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
答案 0 :(得分:2)
用以下内容替换您的版本,并让我知道它是否有效
ids = ["12ab", "13ab", "14ab"]
for x in ids:
url = ("https://google.com/{}".format(x)+"?extraurlparameters")
print(url)
答案 1 :(得分:1)
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)
在第4行中将id更改为x。
答案 2 :(得分:0)
通常,在字符串的末尾调用format()
。
url = "https://google.com/{}?extraurlparameters".format(x)
在Python 3.6+中,您可以使用f-string(格式字符串),例如:
url = f"https://google.com/{x}?extraurlparameters"
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)
答案 3 :(得分:0)
我认为您滥用了格式化功能:
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)