Why don't f-strings play nicely with dictionaries?





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







-3















f-strings don't behave nicely when used with dictionaries, as mentioned here.



Here is an example of the not-so-nice behavior:



d = {'foo': 'bar'}

# Both work as expected
d["foo"]
d['foo']

# This only works when different quotations are used in the inner and outer strings
f'{d["foo"]}'
f"{d['foo']}"

# This doesn't work
f'{d['foo']}'
f"{d["foo"]}"

# The .format() method doesn't care
'{}'.format(d['foo'])


The last two f-strings listed result in a SyntaxError: invalid syntax, which happens because the string '{d['foo']}' is evaluated as '{d['foo']}'.



What is the underlying reason everything inside the curly brackets of f-strings doesn't get evaluated separately, as when using the old .format() method, and what could possibly be the reason for implementing f-strings in this way?



I love f-strings, but this seems like a point in favor of the old method.










share|improve this question


















  • 1





    How would you mark the end of the string if ' didn't mean '?

    – Peter Wood
    Nov 23 '18 at 15:34











  • See answer here stackoverflow.com/questions/4630465/…

    – yoonghm
    Nov 23 '18 at 15:36


















-3















f-strings don't behave nicely when used with dictionaries, as mentioned here.



Here is an example of the not-so-nice behavior:



d = {'foo': 'bar'}

# Both work as expected
d["foo"]
d['foo']

# This only works when different quotations are used in the inner and outer strings
f'{d["foo"]}'
f"{d['foo']}"

# This doesn't work
f'{d['foo']}'
f"{d["foo"]}"

# The .format() method doesn't care
'{}'.format(d['foo'])


The last two f-strings listed result in a SyntaxError: invalid syntax, which happens because the string '{d['foo']}' is evaluated as '{d['foo']}'.



What is the underlying reason everything inside the curly brackets of f-strings doesn't get evaluated separately, as when using the old .format() method, and what could possibly be the reason for implementing f-strings in this way?



I love f-strings, but this seems like a point in favor of the old method.










share|improve this question


















  • 1





    How would you mark the end of the string if ' didn't mean '?

    – Peter Wood
    Nov 23 '18 at 15:34











  • See answer here stackoverflow.com/questions/4630465/…

    – yoonghm
    Nov 23 '18 at 15:36














-3












-3








-3








f-strings don't behave nicely when used with dictionaries, as mentioned here.



Here is an example of the not-so-nice behavior:



d = {'foo': 'bar'}

# Both work as expected
d["foo"]
d['foo']

# This only works when different quotations are used in the inner and outer strings
f'{d["foo"]}'
f"{d['foo']}"

# This doesn't work
f'{d['foo']}'
f"{d["foo"]}"

# The .format() method doesn't care
'{}'.format(d['foo'])


The last two f-strings listed result in a SyntaxError: invalid syntax, which happens because the string '{d['foo']}' is evaluated as '{d['foo']}'.



What is the underlying reason everything inside the curly brackets of f-strings doesn't get evaluated separately, as when using the old .format() method, and what could possibly be the reason for implementing f-strings in this way?



I love f-strings, but this seems like a point in favor of the old method.










share|improve this question














f-strings don't behave nicely when used with dictionaries, as mentioned here.



Here is an example of the not-so-nice behavior:



d = {'foo': 'bar'}

# Both work as expected
d["foo"]
d['foo']

# This only works when different quotations are used in the inner and outer strings
f'{d["foo"]}'
f"{d['foo']}"

# This doesn't work
f'{d['foo']}'
f"{d["foo"]}"

# The .format() method doesn't care
'{}'.format(d['foo'])


The last two f-strings listed result in a SyntaxError: invalid syntax, which happens because the string '{d['foo']}' is evaluated as '{d['foo']}'.



What is the underlying reason everything inside the curly brackets of f-strings doesn't get evaluated separately, as when using the old .format() method, and what could possibly be the reason for implementing f-strings in this way?



I love f-strings, but this seems like a point in favor of the old method.







python string python-3.x syntax-error






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 23 '18 at 15:26









OfficialThrowawayOfficialThrowaway

193




193








  • 1





    How would you mark the end of the string if ' didn't mean '?

    – Peter Wood
    Nov 23 '18 at 15:34











  • See answer here stackoverflow.com/questions/4630465/…

    – yoonghm
    Nov 23 '18 at 15:36














  • 1





    How would you mark the end of the string if ' didn't mean '?

    – Peter Wood
    Nov 23 '18 at 15:34











  • See answer here stackoverflow.com/questions/4630465/…

    – yoonghm
    Nov 23 '18 at 15:36








1




1





How would you mark the end of the string if ' didn't mean '?

– Peter Wood
Nov 23 '18 at 15:34





How would you mark the end of the string if ' didn't mean '?

– Peter Wood
Nov 23 '18 at 15:34













See answer here stackoverflow.com/questions/4630465/…

– yoonghm
Nov 23 '18 at 15:36





See answer here stackoverflow.com/questions/4630465/…

– yoonghm
Nov 23 '18 at 15:36












2 Answers
2






active

oldest

votes


















0














One traditional way of including quotes within quotes is to use a backslash. But PEP498 forbids backslashes in expressions within f-strings:




Backslashes may not appear inside the expression portions of
f-strings...You can use a different type of quote inside the expression...




Therefore, the only way left to access a dictionary value given a key in an f-string expression is to use a different type quote. Using single quotes, or double quotes, everywhere is ambiguous and gives SyntaxError.



str.format is a regular method, and as such works differently: d['foo'] is evaluated before the string is constructed. Just like when you feed arguments to a function, the arguments are evaluated before the function does anything.






share|improve this answer

































    0














    This has nothing to do with f-strings. f strings are common strings once evaluated. What you are trying would be a problem with standard strings too



    The problem is that



    'a "b" c' 


    is declares the literal a "b" c



    while



    'a 'b' c'


    the quotes close and reopen. So, it is equivalent to string a, followed by variable b, followed by string c.



    That's the whole reason python supports both types of quotation marks






    share|improve this answer
























      Your Answer






      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: "1"
      };
      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: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      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%2fstackoverflow.com%2fquestions%2f53449308%2fwhy-dont-f-strings-play-nicely-with-dictionaries%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









      0














      One traditional way of including quotes within quotes is to use a backslash. But PEP498 forbids backslashes in expressions within f-strings:




      Backslashes may not appear inside the expression portions of
      f-strings...You can use a different type of quote inside the expression...




      Therefore, the only way left to access a dictionary value given a key in an f-string expression is to use a different type quote. Using single quotes, or double quotes, everywhere is ambiguous and gives SyntaxError.



      str.format is a regular method, and as such works differently: d['foo'] is evaluated before the string is constructed. Just like when you feed arguments to a function, the arguments are evaluated before the function does anything.






      share|improve this answer






























        0














        One traditional way of including quotes within quotes is to use a backslash. But PEP498 forbids backslashes in expressions within f-strings:




        Backslashes may not appear inside the expression portions of
        f-strings...You can use a different type of quote inside the expression...




        Therefore, the only way left to access a dictionary value given a key in an f-string expression is to use a different type quote. Using single quotes, or double quotes, everywhere is ambiguous and gives SyntaxError.



        str.format is a regular method, and as such works differently: d['foo'] is evaluated before the string is constructed. Just like when you feed arguments to a function, the arguments are evaluated before the function does anything.






        share|improve this answer




























          0












          0








          0







          One traditional way of including quotes within quotes is to use a backslash. But PEP498 forbids backslashes in expressions within f-strings:




          Backslashes may not appear inside the expression portions of
          f-strings...You can use a different type of quote inside the expression...




          Therefore, the only way left to access a dictionary value given a key in an f-string expression is to use a different type quote. Using single quotes, or double quotes, everywhere is ambiguous and gives SyntaxError.



          str.format is a regular method, and as such works differently: d['foo'] is evaluated before the string is constructed. Just like when you feed arguments to a function, the arguments are evaluated before the function does anything.






          share|improve this answer















          One traditional way of including quotes within quotes is to use a backslash. But PEP498 forbids backslashes in expressions within f-strings:




          Backslashes may not appear inside the expression portions of
          f-strings...You can use a different type of quote inside the expression...




          Therefore, the only way left to access a dictionary value given a key in an f-string expression is to use a different type quote. Using single quotes, or double quotes, everywhere is ambiguous and gives SyntaxError.



          str.format is a regular method, and as such works differently: d['foo'] is evaluated before the string is constructed. Just like when you feed arguments to a function, the arguments are evaluated before the function does anything.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 23 '18 at 16:08

























          answered Nov 23 '18 at 15:35









          jppjpp

          103k2166116




          103k2166116

























              0














              This has nothing to do with f-strings. f strings are common strings once evaluated. What you are trying would be a problem with standard strings too



              The problem is that



              'a "b" c' 


              is declares the literal a "b" c



              while



              'a 'b' c'


              the quotes close and reopen. So, it is equivalent to string a, followed by variable b, followed by string c.



              That's the whole reason python supports both types of quotation marks






              share|improve this answer




























                0














                This has nothing to do with f-strings. f strings are common strings once evaluated. What you are trying would be a problem with standard strings too



                The problem is that



                'a "b" c' 


                is declares the literal a "b" c



                while



                'a 'b' c'


                the quotes close and reopen. So, it is equivalent to string a, followed by variable b, followed by string c.



                That's the whole reason python supports both types of quotation marks






                share|improve this answer


























                  0












                  0








                  0







                  This has nothing to do with f-strings. f strings are common strings once evaluated. What you are trying would be a problem with standard strings too



                  The problem is that



                  'a "b" c' 


                  is declares the literal a "b" c



                  while



                  'a 'b' c'


                  the quotes close and reopen. So, it is equivalent to string a, followed by variable b, followed by string c.



                  That's the whole reason python supports both types of quotation marks






                  share|improve this answer













                  This has nothing to do with f-strings. f strings are common strings once evaluated. What you are trying would be a problem with standard strings too



                  The problem is that



                  'a "b" c' 


                  is declares the literal a "b" c



                  while



                  'a 'b' c'


                  the quotes close and reopen. So, it is equivalent to string a, followed by variable b, followed by string c.



                  That's the whole reason python supports both types of quotation marks







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 23 '18 at 15:34









                  blue_noteblue_note

                  12.4k32536




                  12.4k32536






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • 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%2fstackoverflow.com%2fquestions%2f53449308%2fwhy-dont-f-strings-play-nicely-with-dictionaries%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







                      這個網誌中的熱門文章

                      Tangent Lines Diagram Along Smooth Curve

                      Yusuf al-Mu'taman ibn Hud

                      Zucchini