python列表以格式化和替换数据

时间:2018-10-11 19:36:22

标签: python python-3.6

从网站请求数据将返回一个类似于以下的列表。

[
     "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)

1 个答案:

答案 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]