Generating strings dynamically in Python












7












$begingroup$


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&user=boo

  • If user and active are specified, my desired output is: /hey?user=boo&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 += "&file=" + file;

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

if active:
if isFirst:
ep+= "?active=" + str(active);
isFirst = False;
else: ep += "&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.










share|improve this question











$endgroup$








  • 8




    $begingroup$
    Lose the ;. makes python look ugly
    $endgroup$
    – hjpotter92
    Dec 17 '18 at 14:00
















7












$begingroup$


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&user=boo

  • If user and active are specified, my desired output is: /hey?user=boo&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 += "&file=" + file;

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

if active:
if isFirst:
ep+= "?active=" + str(active);
isFirst = False;
else: ep += "&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.










share|improve this question











$endgroup$








  • 8




    $begingroup$
    Lose the ;. makes python look ugly
    $endgroup$
    – hjpotter92
    Dec 17 '18 at 14:00














7












7








7


1



$begingroup$


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&user=boo

  • If user and active are specified, my desired output is: /hey?user=boo&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 += "&file=" + file;

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

if active:
if isFirst:
ep+= "?active=" + str(active);
isFirst = False;
else: ep += "&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.










share|improve this question











$endgroup$




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&user=boo

  • If user and active are specified, my desired output is: /hey?user=boo&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 += "&file=" + file;

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

if active:
if isFirst:
ep+= "?active=" + str(active);
isFirst = False;
else: ep += "&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.







python strings






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Dec 17 '18 at 10:09







Avión

















asked Dec 17 '18 at 9:53









AviónAvión

1486




1486








  • 8




    $begingroup$
    Lose the ;. makes python look ugly
    $endgroup$
    – hjpotter92
    Dec 17 '18 at 14:00














  • 8




    $begingroup$
    Lose the ;. makes python look ugly
    $endgroup$
    – hjpotter92
    Dec 17 '18 at 14:00








8




8




$begingroup$
Lose the ;. makes python look ugly
$endgroup$
– hjpotter92
Dec 17 '18 at 14:00




$begingroup$
Lose the ;. makes python look ugly
$endgroup$
– hjpotter92
Dec 17 '18 at 14:00










2 Answers
2






active

oldest

votes


















12












$begingroup$

The most Pythonic version of this depends a bit on what you do with that URL afterwards. If you are using the requests module (which you probably should), this is already built-in by specifying the params keyword:



import requests

URL = "https://example.com/hey"

r1 = requests.get(URL, params={"file": "example"})
print(r1.url)
# https://example.com/hey?file=example

r2 = requests.get(URL, params={"file": "example", "user": "boo"})
print(r2.url)
# https://example.com/hey?file=example&user=boo

r3 = requests.get(URL, params={"user": "boo", "active": 1})
print(r3.url)
# https://example.com/hey?user=boo&active=1

r4 = requests.get(URL, params={})
print(r4.url)
# https://example.com/hey




If you do need a pure Python solution without any imports, this is what I would do:



def get_url(base_url, **kwargs):
if not kwargs:
return base_url
params = "&".join(f"{key}={value}" for key, value in kwargs.items())
return base_url + "?" + params


Of course this does not urlencode the keys and values and may therefore be a security risk or fail unexpectedly, but neither does your code.



Example usage:



print(get_url("/hey", file="example"))
# /hey?file=example

print(get_url("/hey", file="example", user="boo"))
# /hey?file=example&user=boo

print(get_url("/hey", user="boo", active=1))
# /hey?user=boo&active=1

print(get_url("/hey"))
# /hey





share|improve this answer











$endgroup$













  • $begingroup$
    Due to the implementation of the rest of the code, I need to do it everything without any requests module, just improving the code I posted using strings.
    $endgroup$
    – Avión
    Dec 17 '18 at 10:09






  • 2




    $begingroup$
    @Avión: Just did. It captures all keyword arguments you pass to the function into one dictionary.
    $endgroup$
    – Graipher
    Dec 17 '18 at 10:13






  • 4




    $begingroup$
    Your code is good for illustrative purposes but it fails to URLencode the parameters and is therefore a potential security risk.
    $endgroup$
    – Konrad Rudolph
    Dec 17 '18 at 14:35






  • 1




    $begingroup$
    @KonradRudolph Added a short disclaimer regarding that.
    $endgroup$
    – Graipher
    Dec 17 '18 at 14:38






  • 1




    $begingroup$
    It's not just that it's a security risk, it's also that if you have & in one of the values, it will fail to send the correct value (and most likely fail in general, unless there's also another = in the values).
    $endgroup$
    – ChatterOne
    Dec 18 '18 at 8:33



















18












$begingroup$

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:



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





share|improve this answer









$endgroup$













    Your Answer





    StackExchange.ifUsing("editor", function () {
    return StackExchange.using("mathjaxEditing", function () {
    StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
    StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
    });
    });
    }, "mathjax-editing");

    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "196"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: false,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f209816%2fgenerating-strings-dynamically-in-python%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    12












    $begingroup$

    The most Pythonic version of this depends a bit on what you do with that URL afterwards. If you are using the requests module (which you probably should), this is already built-in by specifying the params keyword:



    import requests

    URL = "https://example.com/hey"

    r1 = requests.get(URL, params={"file": "example"})
    print(r1.url)
    # https://example.com/hey?file=example

    r2 = requests.get(URL, params={"file": "example", "user": "boo"})
    print(r2.url)
    # https://example.com/hey?file=example&user=boo

    r3 = requests.get(URL, params={"user": "boo", "active": 1})
    print(r3.url)
    # https://example.com/hey?user=boo&active=1

    r4 = requests.get(URL, params={})
    print(r4.url)
    # https://example.com/hey




    If you do need a pure Python solution without any imports, this is what I would do:



    def get_url(base_url, **kwargs):
    if not kwargs:
    return base_url
    params = "&".join(f"{key}={value}" for key, value in kwargs.items())
    return base_url + "?" + params


    Of course this does not urlencode the keys and values and may therefore be a security risk or fail unexpectedly, but neither does your code.



    Example usage:



    print(get_url("/hey", file="example"))
    # /hey?file=example

    print(get_url("/hey", file="example", user="boo"))
    # /hey?file=example&user=boo

    print(get_url("/hey", user="boo", active=1))
    # /hey?user=boo&active=1

    print(get_url("/hey"))
    # /hey





    share|improve this answer











    $endgroup$













    • $begingroup$
      Due to the implementation of the rest of the code, I need to do it everything without any requests module, just improving the code I posted using strings.
      $endgroup$
      – Avión
      Dec 17 '18 at 10:09






    • 2




      $begingroup$
      @Avión: Just did. It captures all keyword arguments you pass to the function into one dictionary.
      $endgroup$
      – Graipher
      Dec 17 '18 at 10:13






    • 4




      $begingroup$
      Your code is good for illustrative purposes but it fails to URLencode the parameters and is therefore a potential security risk.
      $endgroup$
      – Konrad Rudolph
      Dec 17 '18 at 14:35






    • 1




      $begingroup$
      @KonradRudolph Added a short disclaimer regarding that.
      $endgroup$
      – Graipher
      Dec 17 '18 at 14:38






    • 1




      $begingroup$
      It's not just that it's a security risk, it's also that if you have & in one of the values, it will fail to send the correct value (and most likely fail in general, unless there's also another = in the values).
      $endgroup$
      – ChatterOne
      Dec 18 '18 at 8:33
















    12












    $begingroup$

    The most Pythonic version of this depends a bit on what you do with that URL afterwards. If you are using the requests module (which you probably should), this is already built-in by specifying the params keyword:



    import requests

    URL = "https://example.com/hey"

    r1 = requests.get(URL, params={"file": "example"})
    print(r1.url)
    # https://example.com/hey?file=example

    r2 = requests.get(URL, params={"file": "example", "user": "boo"})
    print(r2.url)
    # https://example.com/hey?file=example&user=boo

    r3 = requests.get(URL, params={"user": "boo", "active": 1})
    print(r3.url)
    # https://example.com/hey?user=boo&active=1

    r4 = requests.get(URL, params={})
    print(r4.url)
    # https://example.com/hey




    If you do need a pure Python solution without any imports, this is what I would do:



    def get_url(base_url, **kwargs):
    if not kwargs:
    return base_url
    params = "&".join(f"{key}={value}" for key, value in kwargs.items())
    return base_url + "?" + params


    Of course this does not urlencode the keys and values and may therefore be a security risk or fail unexpectedly, but neither does your code.



    Example usage:



    print(get_url("/hey", file="example"))
    # /hey?file=example

    print(get_url("/hey", file="example", user="boo"))
    # /hey?file=example&user=boo

    print(get_url("/hey", user="boo", active=1))
    # /hey?user=boo&active=1

    print(get_url("/hey"))
    # /hey





    share|improve this answer











    $endgroup$













    • $begingroup$
      Due to the implementation of the rest of the code, I need to do it everything without any requests module, just improving the code I posted using strings.
      $endgroup$
      – Avión
      Dec 17 '18 at 10:09






    • 2




      $begingroup$
      @Avión: Just did. It captures all keyword arguments you pass to the function into one dictionary.
      $endgroup$
      – Graipher
      Dec 17 '18 at 10:13






    • 4




      $begingroup$
      Your code is good for illustrative purposes but it fails to URLencode the parameters and is therefore a potential security risk.
      $endgroup$
      – Konrad Rudolph
      Dec 17 '18 at 14:35






    • 1




      $begingroup$
      @KonradRudolph Added a short disclaimer regarding that.
      $endgroup$
      – Graipher
      Dec 17 '18 at 14:38






    • 1




      $begingroup$
      It's not just that it's a security risk, it's also that if you have & in one of the values, it will fail to send the correct value (and most likely fail in general, unless there's also another = in the values).
      $endgroup$
      – ChatterOne
      Dec 18 '18 at 8:33














    12












    12








    12





    $begingroup$

    The most Pythonic version of this depends a bit on what you do with that URL afterwards. If you are using the requests module (which you probably should), this is already built-in by specifying the params keyword:



    import requests

    URL = "https://example.com/hey"

    r1 = requests.get(URL, params={"file": "example"})
    print(r1.url)
    # https://example.com/hey?file=example

    r2 = requests.get(URL, params={"file": "example", "user": "boo"})
    print(r2.url)
    # https://example.com/hey?file=example&user=boo

    r3 = requests.get(URL, params={"user": "boo", "active": 1})
    print(r3.url)
    # https://example.com/hey?user=boo&active=1

    r4 = requests.get(URL, params={})
    print(r4.url)
    # https://example.com/hey




    If you do need a pure Python solution without any imports, this is what I would do:



    def get_url(base_url, **kwargs):
    if not kwargs:
    return base_url
    params = "&".join(f"{key}={value}" for key, value in kwargs.items())
    return base_url + "?" + params


    Of course this does not urlencode the keys and values and may therefore be a security risk or fail unexpectedly, but neither does your code.



    Example usage:



    print(get_url("/hey", file="example"))
    # /hey?file=example

    print(get_url("/hey", file="example", user="boo"))
    # /hey?file=example&user=boo

    print(get_url("/hey", user="boo", active=1))
    # /hey?user=boo&active=1

    print(get_url("/hey"))
    # /hey





    share|improve this answer











    $endgroup$



    The most Pythonic version of this depends a bit on what you do with that URL afterwards. If you are using the requests module (which you probably should), this is already built-in by specifying the params keyword:



    import requests

    URL = "https://example.com/hey"

    r1 = requests.get(URL, params={"file": "example"})
    print(r1.url)
    # https://example.com/hey?file=example

    r2 = requests.get(URL, params={"file": "example", "user": "boo"})
    print(r2.url)
    # https://example.com/hey?file=example&user=boo

    r3 = requests.get(URL, params={"user": "boo", "active": 1})
    print(r3.url)
    # https://example.com/hey?user=boo&active=1

    r4 = requests.get(URL, params={})
    print(r4.url)
    # https://example.com/hey




    If you do need a pure Python solution without any imports, this is what I would do:



    def get_url(base_url, **kwargs):
    if not kwargs:
    return base_url
    params = "&".join(f"{key}={value}" for key, value in kwargs.items())
    return base_url + "?" + params


    Of course this does not urlencode the keys and values and may therefore be a security risk or fail unexpectedly, but neither does your code.



    Example usage:



    print(get_url("/hey", file="example"))
    # /hey?file=example

    print(get_url("/hey", file="example", user="boo"))
    # /hey?file=example&user=boo

    print(get_url("/hey", user="boo", active=1))
    # /hey?user=boo&active=1

    print(get_url("/hey"))
    # /hey






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Dec 18 '18 at 8:52

























    answered Dec 17 '18 at 10:07









    GraipherGraipher

    25.9k54090




    25.9k54090












    • $begingroup$
      Due to the implementation of the rest of the code, I need to do it everything without any requests module, just improving the code I posted using strings.
      $endgroup$
      – Avión
      Dec 17 '18 at 10:09






    • 2




      $begingroup$
      @Avión: Just did. It captures all keyword arguments you pass to the function into one dictionary.
      $endgroup$
      – Graipher
      Dec 17 '18 at 10:13






    • 4




      $begingroup$
      Your code is good for illustrative purposes but it fails to URLencode the parameters and is therefore a potential security risk.
      $endgroup$
      – Konrad Rudolph
      Dec 17 '18 at 14:35






    • 1




      $begingroup$
      @KonradRudolph Added a short disclaimer regarding that.
      $endgroup$
      – Graipher
      Dec 17 '18 at 14:38






    • 1




      $begingroup$
      It's not just that it's a security risk, it's also that if you have & in one of the values, it will fail to send the correct value (and most likely fail in general, unless there's also another = in the values).
      $endgroup$
      – ChatterOne
      Dec 18 '18 at 8:33


















    • $begingroup$
      Due to the implementation of the rest of the code, I need to do it everything without any requests module, just improving the code I posted using strings.
      $endgroup$
      – Avión
      Dec 17 '18 at 10:09






    • 2




      $begingroup$
      @Avión: Just did. It captures all keyword arguments you pass to the function into one dictionary.
      $endgroup$
      – Graipher
      Dec 17 '18 at 10:13






    • 4




      $begingroup$
      Your code is good for illustrative purposes but it fails to URLencode the parameters and is therefore a potential security risk.
      $endgroup$
      – Konrad Rudolph
      Dec 17 '18 at 14:35






    • 1




      $begingroup$
      @KonradRudolph Added a short disclaimer regarding that.
      $endgroup$
      – Graipher
      Dec 17 '18 at 14:38






    • 1




      $begingroup$
      It's not just that it's a security risk, it's also that if you have & in one of the values, it will fail to send the correct value (and most likely fail in general, unless there's also another = in the values).
      $endgroup$
      – ChatterOne
      Dec 18 '18 at 8:33
















    $begingroup$
    Due to the implementation of the rest of the code, I need to do it everything without any requests module, just improving the code I posted using strings.
    $endgroup$
    – Avión
    Dec 17 '18 at 10:09




    $begingroup$
    Due to the implementation of the rest of the code, I need to do it everything without any requests module, just improving the code I posted using strings.
    $endgroup$
    – Avión
    Dec 17 '18 at 10:09




    2




    2




    $begingroup$
    @Avión: Just did. It captures all keyword arguments you pass to the function into one dictionary.
    $endgroup$
    – Graipher
    Dec 17 '18 at 10:13




    $begingroup$
    @Avión: Just did. It captures all keyword arguments you pass to the function into one dictionary.
    $endgroup$
    – Graipher
    Dec 17 '18 at 10:13




    4




    4




    $begingroup$
    Your code is good for illustrative purposes but it fails to URLencode the parameters and is therefore a potential security risk.
    $endgroup$
    – Konrad Rudolph
    Dec 17 '18 at 14:35




    $begingroup$
    Your code is good for illustrative purposes but it fails to URLencode the parameters and is therefore a potential security risk.
    $endgroup$
    – Konrad Rudolph
    Dec 17 '18 at 14:35




    1




    1




    $begingroup$
    @KonradRudolph Added a short disclaimer regarding that.
    $endgroup$
    – Graipher
    Dec 17 '18 at 14:38




    $begingroup$
    @KonradRudolph Added a short disclaimer regarding that.
    $endgroup$
    – Graipher
    Dec 17 '18 at 14:38




    1




    1




    $begingroup$
    It's not just that it's a security risk, it's also that if you have & in one of the values, it will fail to send the correct value (and most likely fail in general, unless there's also another = in the values).
    $endgroup$
    – ChatterOne
    Dec 18 '18 at 8:33




    $begingroup$
    It's not just that it's a security risk, it's also that if you have & in one of the values, it will fail to send the correct value (and most likely fail in general, unless there's also another = in the values).
    $endgroup$
    – ChatterOne
    Dec 18 '18 at 8:33













    18












    $begingroup$

    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:



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





    share|improve this answer









    $endgroup$


















      18












      $begingroup$

      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:



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





      share|improve this answer









      $endgroup$
















        18












        18








        18





        $begingroup$

        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:



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





        share|improve this answer









        $endgroup$



        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:



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






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Dec 17 '18 at 10:12









        Mathias EttingerMathias Ettinger

        25.1k33185




        25.1k33185






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Code Review Stack Exchange!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            Use MathJax to format equations. MathJax reference.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f209816%2fgenerating-strings-dynamically-in-python%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Le Mesnil-Réaume

            Ida-Boy-Ed-Garten

            web3.py web3.isConnected() returns false always