python list to format and replace data
Requesting data from a website returns a list which looks like this.
[ "https://site1.com/:hash", "https://site2.com/:hash", "https://site3.com/:hash", "https://site4.com/:hash", "https://site5.com/:hash" ]
I'm trying to loop over the list and replace the :hash with my a variable that equals cats. The extra formatting from the list along with the extra punctuation and the search/replace has me stumped. Any additional help would be greatly appreciated.
Final Result Requested
https://site1.com/cats https://site2.com/cats https://site3.com/cats https://site4.com/cats https://site5.com/cats
So far I have the following
#!/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)
Python has a handy
string.replace()function. All you need to do is iterate over the list of URLs and call the method on each object.
for url in urls: url.replace(':hash', 'cats')
ais the initial list, use list comprehension:
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]