Eb J
Eb J

Reputation: 223

Dynamic String formatting while looping - python

I have been looking for a graceful way to dynamically format strings (URLs) in Python while looping... This is for when I want to request using different query parameters for each.

For example, this is what I've been resorting to at the moment (assuming I have 3 URLs):

for i in range(3):
    for num in range(0, 496, 5):
        if i == 1:
            requests.get('https://my-website.com?pricefrom={}&priceto={}'.format(num, num + 5))

        if i == 2:
            requests.get('https://my-website.com?qtyfrom={}&qtyto={}'.format(num, num + 5))

        # ......... :(

This is just ugly and I don't want to imagine what I'd do in the scenario where I have more links to request to.

Isn't there a solution simpler/more graceful like this for example:

urls = [<url1>, <url2>,....<url50>] # maybe each url has placeholders

for url in urls:
    # do some magic

Any help would be highly appreciated

Upvotes: 1

Views: 967

Answers (2)

luminousmen
luminousmen

Reputation: 2169

You can store strings with format in list as you said:

import requests

urls = ['https://example.com?from={fr}&to={to}',
        'https://example1.com?from={fr}&to={to}',
        'https://example2.com?from={fr}&to={to}'
]
for url in urls:
    for num in range(0, 496, 5):
        requests.get(url.format(fr=num, to=num + 5))

Also in python 3.6 you can use f-strings

Upvotes: 2

Eb J
Eb J

Reputation: 223

Thanks to help from @luminousmen and the rest of you guys... I found a solution. Apparently you CAN just add placeholders and not do any operations on them :'D :

urls = ['https://example.com?from={}&to={}', 
        'https://example1.com?from={}&to={}',
        'https://example2.com?from={}&to={}']

for url in urls:
    for num in range(0, 496, 5):
        requests.get(url.format(num, num + 5))

Upvotes: 0

Related Questions