Generating strings dynamically in Python I'm generating a URL (in string) that depends on 3 optional parameters, file, user and active.

From a base url: /hey I want to generate the endpoint, this means:


If file is specificied, my desired output would is: /hey?file=example
If file and user is specified, my desired output is: /hey?file=example&amp;user=boo
If user and active are specified, my desired output is: /hey?user=boo&amp;active=1 
If no optional parameters are specified, my desired output is: /hey
and so on with all the combinations...


My code, which is working correctly, is as follows (change the None's at the top if you want to test it):

file = None
user = None
active = 1

ep = "/hey"
isFirst = True

if file:
  if isFirst:
    ep+= "?file=" + file;
    isFirst = False;
  else: ep += "&amp;file=" + file;

if user:
  if isFirst:
    ep+= "?user=" + user;
    isFirst = False;
  else: ep += "&amp;user=" + user;

if active:
  if isFirst:
    ep+= "?active=" + str(active);
    isFirst = False;
  else: ep += "&amp;active=" + str(active);

print ep


Can someone give me a more python implementation for this? I can't use modules as requests.

Thanks in advance.
You're pretty much reinventing urllib.parse.urlencode:

from urllib.parse import urlencode


def prepare_query_string(**kwargs):
    return urlencode([(key, value) for key, value in kwargs.items() if value is not None])


Usage being:

&gt;&gt;&gt; prepare_query_string(active=1)
'active=1'
&gt;&gt;&gt; prepare_query_string(active=1, user=None)
'active=1'
&gt;&gt;&gt; prepare_query_string(active=1, user='bob')
'active=1&amp;user=bob'
&gt;&gt;&gt; prepare_query_string(file='foo.tar.gz', user='bob')
'file=foo.tar.gz&amp;user=bob'
&gt;&gt;&gt; prepare_query_string(file='foo.tar.gz', user='bob', active=None)
'file=foo.tar.gz&amp;user=bob'
&gt;&gt;&gt; prepare_query_string(file='foo.tar.gz', user='bob', active=1)
'file=foo.tar.gz&amp;user=bob&amp;active=1'