python - 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)
.
解决方案
如果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]
推荐阅读
- python - 计算模型语法中 City 对象的实例数
- kubernetes - kubernetes DNS - 让服务通过 DNS 联系自己
- c++ - 写入文件时需要帮助换行
- java - 即使转到不同的 Activity,也可以从 Main Activity 继续 Fragment 中的媒体播放器(播放歌曲)
- keyboard - 绑定到键时,xdotool 无法在 i3wm 中工作
- java - Firebase 远程配置 - 安卓
- html - 滑块顶部不同设备尺寸的响应式徽标
- oracle - 如何创建在 oracle apex 报告中右键单击时出现的上下文菜单?
- python - 在 Pycharm Python virtualenv 中使用 subprocess.call() -- 如何为子进程停用 venv
- python - Django 表单:来自外键的引用字段