从网站请求数据将返回一个类似于以下的列表。
[
"https://site1.com/:hash",
"https://site2.com/:hash",
"https://site3.com/:hash",
"https://site4.com/:hash",
"https://site5.com/:hash"
]
我试图遍历该列表,并用一个等于 cats 的变量替换:hash 。从列表的额外格式,加上额外的标点符号和搜索/替换,我感到很困惑。任何其他帮助将不胜感激。
https://site1.com/cats
https://site2.com/cats
https://site3.com/cats
https://site4.com/cats
https://site5.com/cats
#!/usr/bin/env python3
import os
import requests
gw_path = 'https://raw.githubusercontent.com/ipfs/public-gateway-checker/master/gateways.json'
r = requests.get(gw_path)
text = r.text
for item in text:
mod = item.replace(':hash', 'cats')
print(mod)
。
答案 0 :(得分:0)
如果a
是初始列表,请使用列表理解:
a = ["https://site1.com/:hash",
"https://site2.com/:hash",
"https://site3.com/:hash",
"https://site4.com/:hash",
"https://site5.com/:hash"]
modified_a = [i.replace(':hash', 'cats') for i in a]
modified_a
['https://site1.com/cats',
'https://site2.com/cats',
'https://site3.com/cats',
'https://site4.com/cats',
'https://site5.com/cats']
并且:
print "[%s]" % (','.join(modified_a)
[https://site1.com/cats,https://site2.com/cats,https://site3.com/cats,https://site4.com/cats,https://site5.com/cats]