HectorOfTroy407
HectorOfTroy407

Reputation: 1897

Python Dynamically Create String Based on Input

Looking for an elegant way to create a URL by reading in values from a config file.

If I have the following three fields in a config file:

query1=
query2=
query3=

And I want to add them to a BASE_URL if they exist, what is an elegant way to do this?

I know there is an ugly answer like:

url +='?query1={}'.format(param1) if param1 and Not param2 or param3
url +='?query1={}&query2={}'.format(param1,param2) if param1 and param2 and Not param3
etc...

Is there an elegant pythonic solution to this? A way to abstract this idea? Thank you.

Upvotes: 0

Views: 755

Answers (2)

Sevy
Sevy

Reputation: 698

One way to do this, if you're a fan of list comprehensions like I am:

params = [param1,param2,param3]

query_array = ['query%d=%s'%(ii+1,param) for ii,param in enumerate(params) if param]
url += '?'+'&'.join(query_array)

This will eliminate the need to check all the params individually to see if they exist

Upvotes: 1

DYZ
DYZ

Reputation: 57033

Store the fields in a dictionary as "key:value" pairs (you can read the file as dictionary using CSV reader) and append them to the base URL if needed:

fields = {'query1' : 'value1', 'query2' : '', 'query3' : 5, ...}
if fields: # Avoid null fields
    url += '?' + '&'.join('{}={}'.format(k,v) for k,v in fields.items() if v)
# '...?query1=value1&query3=5'

Upvotes: 1

Related Questions