Generating strings dynamically in Python











up vote
2
down vote

favorite












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




























    up vote
    2
    down vote

    favorite












    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


























      up vote
      2
      down vote

      favorite









      up vote
      2
      down vote

      favorite











      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















      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 14 mins ago

























      asked 31 mins ago









      Avión

      1235




      1235






















          2 Answers
          2






          active

          oldest

          votes

















          up vote
          0
          down vote



          accepted










          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/"

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

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

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

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




          If you do need a pure Python solution, 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


          To be a bit safer, you might want to use urllib.urlencode on the values to ensure that spaces etc are correctly translated (requests does that for you, so there it is not needed).



          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























          • 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.
            – Avión
            15 mins ago










          • Can you please give me a simple example of how to use the get_url function please? The **kwargs part is a bit hard for me to understand. Thank you!
            – Avión
            12 mins ago










          • @Avión: Just did. It captures all keyword arguments you pass to the function into one dictionary.
            – Graipher
            11 mins ago


















          up vote
          2
          down vote













          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





















            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',
            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








            up vote
            0
            down vote



            accepted










            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/"

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

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

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

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




            If you do need a pure Python solution, 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


            To be a bit safer, you might want to use urllib.urlencode on the values to ensure that spaces etc are correctly translated (requests does that for you, so there it is not needed).



            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























            • 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.
              – Avión
              15 mins ago










            • Can you please give me a simple example of how to use the get_url function please? The **kwargs part is a bit hard for me to understand. Thank you!
              – Avión
              12 mins ago










            • @Avión: Just did. It captures all keyword arguments you pass to the function into one dictionary.
              – Graipher
              11 mins ago















            up vote
            0
            down vote



            accepted










            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/"

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

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

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

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




            If you do need a pure Python solution, 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


            To be a bit safer, you might want to use urllib.urlencode on the values to ensure that spaces etc are correctly translated (requests does that for you, so there it is not needed).



            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























            • 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.
              – Avión
              15 mins ago










            • Can you please give me a simple example of how to use the get_url function please? The **kwargs part is a bit hard for me to understand. Thank you!
              – Avión
              12 mins ago










            • @Avión: Just did. It captures all keyword arguments you pass to the function into one dictionary.
              – Graipher
              11 mins ago













            up vote
            0
            down vote



            accepted







            up vote
            0
            down vote



            accepted






            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/"

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

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

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

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




            If you do need a pure Python solution, 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


            To be a bit safer, you might want to use urllib.urlencode on the values to ensure that spaces etc are correctly translated (requests does that for you, so there it is not needed).



            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














            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/"

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

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

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

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




            If you do need a pure Python solution, 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


            To be a bit safer, you might want to use urllib.urlencode on the values to ensure that spaces etc are correctly translated (requests does that for you, so there it is not needed).



            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 11 mins ago

























            answered 17 mins ago









            Graipher

            23.1k53384




            23.1k53384












            • 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.
              – Avión
              15 mins ago










            • Can you please give me a simple example of how to use the get_url function please? The **kwargs part is a bit hard for me to understand. Thank you!
              – Avión
              12 mins ago










            • @Avión: Just did. It captures all keyword arguments you pass to the function into one dictionary.
              – Graipher
              11 mins ago


















            • 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.
              – Avión
              15 mins ago










            • Can you please give me a simple example of how to use the get_url function please? The **kwargs part is a bit hard for me to understand. Thank you!
              – Avión
              12 mins ago










            • @Avión: Just did. It captures all keyword arguments you pass to the function into one dictionary.
              – Graipher
              11 mins ago
















            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.
            – Avión
            15 mins ago




            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.
            – Avión
            15 mins ago












            Can you please give me a simple example of how to use the get_url function please? The **kwargs part is a bit hard for me to understand. Thank you!
            – Avión
            12 mins ago




            Can you please give me a simple example of how to use the get_url function please? The **kwargs part is a bit hard for me to understand. Thank you!
            – Avión
            12 mins ago












            @Avión: Just did. It captures all keyword arguments you pass to the function into one dictionary.
            – Graipher
            11 mins ago




            @Avión: Just did. It captures all keyword arguments you pass to the function into one dictionary.
            – Graipher
            11 mins ago












            up vote
            2
            down vote













            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

























              up vote
              2
              down vote













              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























                up vote
                2
                down vote










                up vote
                2
                down vote









                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












                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 12 mins ago









                Mathias Ettinger

                23.1k33179




                23.1k33179






























                    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.





                    Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                    Please pay close attention to the following guidance:


                    • 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.


                    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

                    Ellipse (mathématiques)

                    Quarter-circle Tiles

                    Mont Emei