首页 > 解决方案 > python列表格式化和替换数据

问题描述

从网站请求数据会返回一个如下所示的列表。

[
     "https://site1.com/:hash",
     "https://site2.com/:hash",
     "https://site3.com/:hash",
     "https://site4.com/:hash",
     "https://site5.com/:hash"
]

我正在尝试遍历列表并将:hash替换为等于cat的变量。列表中的额外格式以及额外的标点符号和搜索/替换让我很难过。任何额外的帮助将不胜感激。

最终结果要求

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)

.

标签: pythonpython-3.6

解决方案


如果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]

推荐阅读