How to apply float precision (type specifier) in a conditional f-string?

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP












9















I have the following f-string I want to print out on the condition the variable is available:



f"Percent growth: self.percent_growth if True else 'No data yet'"


Which results in:



Percent growth : 0.19824077757643577


So normally I'd use a type specifier for float precision like this:



f'self.percent_growth:.2f'


Which would result in:



0.198


But that messes with the if-statement in this case. Either it fails because:



f"Percent profit : self.percent_profit:.2f if True else 'None yet'"


The if statement becomes unreachable.
Or in the second way:



f"Percent profit : self.percent_profit if True else 'None yet':.2f"


The f-string fails whenever the condition leads to the else clause.



So my question is, how can I apply the float precision within the f-string when the f-string can result in two types?










share|improve this question

















  • 1





    I formulated the question this way so it was clear no matter what condition it fails to even execute.

    – NoSplitSherlock
    Mar 1 at 19:32















9















I have the following f-string I want to print out on the condition the variable is available:



f"Percent growth: self.percent_growth if True else 'No data yet'"


Which results in:



Percent growth : 0.19824077757643577


So normally I'd use a type specifier for float precision like this:



f'self.percent_growth:.2f'


Which would result in:



0.198


But that messes with the if-statement in this case. Either it fails because:



f"Percent profit : self.percent_profit:.2f if True else 'None yet'"


The if statement becomes unreachable.
Or in the second way:



f"Percent profit : self.percent_profit if True else 'None yet':.2f"


The f-string fails whenever the condition leads to the else clause.



So my question is, how can I apply the float precision within the f-string when the f-string can result in two types?










share|improve this question

















  • 1





    I formulated the question this way so it was clear no matter what condition it fails to even execute.

    – NoSplitSherlock
    Mar 1 at 19:32













9












9








9








I have the following f-string I want to print out on the condition the variable is available:



f"Percent growth: self.percent_growth if True else 'No data yet'"


Which results in:



Percent growth : 0.19824077757643577


So normally I'd use a type specifier for float precision like this:



f'self.percent_growth:.2f'


Which would result in:



0.198


But that messes with the if-statement in this case. Either it fails because:



f"Percent profit : self.percent_profit:.2f if True else 'None yet'"


The if statement becomes unreachable.
Or in the second way:



f"Percent profit : self.percent_profit if True else 'None yet':.2f"


The f-string fails whenever the condition leads to the else clause.



So my question is, how can I apply the float precision within the f-string when the f-string can result in two types?










share|improve this question














I have the following f-string I want to print out on the condition the variable is available:



f"Percent growth: self.percent_growth if True else 'No data yet'"


Which results in:



Percent growth : 0.19824077757643577


So normally I'd use a type specifier for float precision like this:



f'self.percent_growth:.2f'


Which would result in:



0.198


But that messes with the if-statement in this case. Either it fails because:



f"Percent profit : self.percent_profit:.2f if True else 'None yet'"


The if statement becomes unreachable.
Or in the second way:



f"Percent profit : self.percent_profit if True else 'None yet':.2f"


The f-string fails whenever the condition leads to the else clause.



So my question is, how can I apply the float precision within the f-string when the f-string can result in two types?







python python-3.x f-string






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 1 at 17:53









NoSplitSherlockNoSplitSherlock

423211




423211







  • 1





    I formulated the question this way so it was clear no matter what condition it fails to even execute.

    – NoSplitSherlock
    Mar 1 at 19:32












  • 1





    I formulated the question this way so it was clear no matter what condition it fails to even execute.

    – NoSplitSherlock
    Mar 1 at 19:32







1




1





I formulated the question this way so it was clear no matter what condition it fails to even execute.

– NoSplitSherlock
Mar 1 at 19:32





I formulated the question this way so it was clear no matter what condition it fails to even execute.

– NoSplitSherlock
Mar 1 at 19:32












3 Answers
3






active

oldest

votes


















10














You could use another f-string for your first condition:



f"Percent profit : f'self.percent_profit:.2f' if True else 'None yet'"


Admittedly not ideal, but it does the job.






share|improve this answer


















  • 2





    Another way is using str.format but I don't think it's any different. f"Percent profit : ':.2f'.format(self.percent_format) if True else 'None yet'" This is as simple as it gets if OP insists putting the condition within the f string itself.

    – Idlehands
    Mar 1 at 18:09












  • @Idlehands Isn't it strange though that I can format strings and use conditionals, but not both at the same time?

    – NoSplitSherlock
    Mar 1 at 18:24






  • 1





    @NoSplitSherlock If both outcomes of the the conditional were the same, you could. I think the tricky part of your example is that your conditional will yield either a float or a string.

    – Nikolas Stevenson-Molnar
    Mar 1 at 18:26






  • 1





    @PatrickArtner see the OP’s question and code sample. The if True is a stand in for any conditional.

    – Nikolas Stevenson-Molnar
    Mar 1 at 18:43











  • @PatrickArtner Absolutely, that works too.

    – Nikolas Stevenson-Molnar
    Mar 1 at 18:54


















2














I think the f string within f string answer is as simple as it gets, but if you want a little bit more readability, consider moving the condition outside the f string:



value = f'self.percent_profit:.2f' if True else 'No data yet'
print(f"Percent profit : value")





share|improve this answer






























    2














    You can use a ternary for the formatter as well - no need to stack 2 f-strings like Nikolas answer does:



    for pg in (2.562345678, 0.9, None): # 0.0 is also Falsy - careful ;o)
    print(f"Percent Growth: pg if pg else 'No data yet':'.05f' if pg else ''")
    # you need to put '.05f' into a string for this to work and not complain


    Output:



    Percent growth: 2.56235
    Percent growth: 0.90000
    Percent growth: No data yet





    share|improve this answer




















    • 1





      I love how hacky this is.

      – NoSplitSherlock
      Mar 1 at 19:02











    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%2f54949918%2fhow-to-apply-float-precision-type-specifier-in-a-conditional-f-string%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    3 Answers
    3






    active

    oldest

    votes








    3 Answers
    3






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    10














    You could use another f-string for your first condition:



    f"Percent profit : f'self.percent_profit:.2f' if True else 'None yet'"


    Admittedly not ideal, but it does the job.






    share|improve this answer


















    • 2





      Another way is using str.format but I don't think it's any different. f"Percent profit : ':.2f'.format(self.percent_format) if True else 'None yet'" This is as simple as it gets if OP insists putting the condition within the f string itself.

      – Idlehands
      Mar 1 at 18:09












    • @Idlehands Isn't it strange though that I can format strings and use conditionals, but not both at the same time?

      – NoSplitSherlock
      Mar 1 at 18:24






    • 1





      @NoSplitSherlock If both outcomes of the the conditional were the same, you could. I think the tricky part of your example is that your conditional will yield either a float or a string.

      – Nikolas Stevenson-Molnar
      Mar 1 at 18:26






    • 1





      @PatrickArtner see the OP’s question and code sample. The if True is a stand in for any conditional.

      – Nikolas Stevenson-Molnar
      Mar 1 at 18:43











    • @PatrickArtner Absolutely, that works too.

      – Nikolas Stevenson-Molnar
      Mar 1 at 18:54















    10














    You could use another f-string for your first condition:



    f"Percent profit : f'self.percent_profit:.2f' if True else 'None yet'"


    Admittedly not ideal, but it does the job.






    share|improve this answer


















    • 2





      Another way is using str.format but I don't think it's any different. f"Percent profit : ':.2f'.format(self.percent_format) if True else 'None yet'" This is as simple as it gets if OP insists putting the condition within the f string itself.

      – Idlehands
      Mar 1 at 18:09












    • @Idlehands Isn't it strange though that I can format strings and use conditionals, but not both at the same time?

      – NoSplitSherlock
      Mar 1 at 18:24






    • 1





      @NoSplitSherlock If both outcomes of the the conditional were the same, you could. I think the tricky part of your example is that your conditional will yield either a float or a string.

      – Nikolas Stevenson-Molnar
      Mar 1 at 18:26






    • 1





      @PatrickArtner see the OP’s question and code sample. The if True is a stand in for any conditional.

      – Nikolas Stevenson-Molnar
      Mar 1 at 18:43











    • @PatrickArtner Absolutely, that works too.

      – Nikolas Stevenson-Molnar
      Mar 1 at 18:54













    10












    10








    10







    You could use another f-string for your first condition:



    f"Percent profit : f'self.percent_profit:.2f' if True else 'None yet'"


    Admittedly not ideal, but it does the job.






    share|improve this answer













    You could use another f-string for your first condition:



    f"Percent profit : f'self.percent_profit:.2f' if True else 'None yet'"


    Admittedly not ideal, but it does the job.







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Mar 1 at 17:59









    Nikolas Stevenson-MolnarNikolas Stevenson-Molnar

    1,6101016




    1,6101016







    • 2





      Another way is using str.format but I don't think it's any different. f"Percent profit : ':.2f'.format(self.percent_format) if True else 'None yet'" This is as simple as it gets if OP insists putting the condition within the f string itself.

      – Idlehands
      Mar 1 at 18:09












    • @Idlehands Isn't it strange though that I can format strings and use conditionals, but not both at the same time?

      – NoSplitSherlock
      Mar 1 at 18:24






    • 1





      @NoSplitSherlock If both outcomes of the the conditional were the same, you could. I think the tricky part of your example is that your conditional will yield either a float or a string.

      – Nikolas Stevenson-Molnar
      Mar 1 at 18:26






    • 1





      @PatrickArtner see the OP’s question and code sample. The if True is a stand in for any conditional.

      – Nikolas Stevenson-Molnar
      Mar 1 at 18:43











    • @PatrickArtner Absolutely, that works too.

      – Nikolas Stevenson-Molnar
      Mar 1 at 18:54












    • 2





      Another way is using str.format but I don't think it's any different. f"Percent profit : ':.2f'.format(self.percent_format) if True else 'None yet'" This is as simple as it gets if OP insists putting the condition within the f string itself.

      – Idlehands
      Mar 1 at 18:09












    • @Idlehands Isn't it strange though that I can format strings and use conditionals, but not both at the same time?

      – NoSplitSherlock
      Mar 1 at 18:24






    • 1





      @NoSplitSherlock If both outcomes of the the conditional were the same, you could. I think the tricky part of your example is that your conditional will yield either a float or a string.

      – Nikolas Stevenson-Molnar
      Mar 1 at 18:26






    • 1





      @PatrickArtner see the OP’s question and code sample. The if True is a stand in for any conditional.

      – Nikolas Stevenson-Molnar
      Mar 1 at 18:43











    • @PatrickArtner Absolutely, that works too.

      – Nikolas Stevenson-Molnar
      Mar 1 at 18:54







    2




    2





    Another way is using str.format but I don't think it's any different. f"Percent profit : ':.2f'.format(self.percent_format) if True else 'None yet'" This is as simple as it gets if OP insists putting the condition within the f string itself.

    – Idlehands
    Mar 1 at 18:09






    Another way is using str.format but I don't think it's any different. f"Percent profit : ':.2f'.format(self.percent_format) if True else 'None yet'" This is as simple as it gets if OP insists putting the condition within the f string itself.

    – Idlehands
    Mar 1 at 18:09














    @Idlehands Isn't it strange though that I can format strings and use conditionals, but not both at the same time?

    – NoSplitSherlock
    Mar 1 at 18:24





    @Idlehands Isn't it strange though that I can format strings and use conditionals, but not both at the same time?

    – NoSplitSherlock
    Mar 1 at 18:24




    1




    1





    @NoSplitSherlock If both outcomes of the the conditional were the same, you could. I think the tricky part of your example is that your conditional will yield either a float or a string.

    – Nikolas Stevenson-Molnar
    Mar 1 at 18:26





    @NoSplitSherlock If both outcomes of the the conditional were the same, you could. I think the tricky part of your example is that your conditional will yield either a float or a string.

    – Nikolas Stevenson-Molnar
    Mar 1 at 18:26




    1




    1





    @PatrickArtner see the OP’s question and code sample. The if True is a stand in for any conditional.

    – Nikolas Stevenson-Molnar
    Mar 1 at 18:43





    @PatrickArtner see the OP’s question and code sample. The if True is a stand in for any conditional.

    – Nikolas Stevenson-Molnar
    Mar 1 at 18:43













    @PatrickArtner Absolutely, that works too.

    – Nikolas Stevenson-Molnar
    Mar 1 at 18:54





    @PatrickArtner Absolutely, that works too.

    – Nikolas Stevenson-Molnar
    Mar 1 at 18:54













    2














    I think the f string within f string answer is as simple as it gets, but if you want a little bit more readability, consider moving the condition outside the f string:



    value = f'self.percent_profit:.2f' if True else 'No data yet'
    print(f"Percent profit : value")





    share|improve this answer



























      2














      I think the f string within f string answer is as simple as it gets, but if you want a little bit more readability, consider moving the condition outside the f string:



      value = f'self.percent_profit:.2f' if True else 'No data yet'
      print(f"Percent profit : value")





      share|improve this answer

























        2












        2








        2







        I think the f string within f string answer is as simple as it gets, but if you want a little bit more readability, consider moving the condition outside the f string:



        value = f'self.percent_profit:.2f' if True else 'No data yet'
        print(f"Percent profit : value")





        share|improve this answer













        I think the f string within f string answer is as simple as it gets, but if you want a little bit more readability, consider moving the condition outside the f string:



        value = f'self.percent_profit:.2f' if True else 'No data yet'
        print(f"Percent profit : value")






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 1 at 18:12









        IdlehandsIdlehands

        6,1631923




        6,1631923





















            2














            You can use a ternary for the formatter as well - no need to stack 2 f-strings like Nikolas answer does:



            for pg in (2.562345678, 0.9, None): # 0.0 is also Falsy - careful ;o)
            print(f"Percent Growth: pg if pg else 'No data yet':'.05f' if pg else ''")
            # you need to put '.05f' into a string for this to work and not complain


            Output:



            Percent growth: 2.56235
            Percent growth: 0.90000
            Percent growth: No data yet





            share|improve this answer




















            • 1





              I love how hacky this is.

              – NoSplitSherlock
              Mar 1 at 19:02















            2














            You can use a ternary for the formatter as well - no need to stack 2 f-strings like Nikolas answer does:



            for pg in (2.562345678, 0.9, None): # 0.0 is also Falsy - careful ;o)
            print(f"Percent Growth: pg if pg else 'No data yet':'.05f' if pg else ''")
            # you need to put '.05f' into a string for this to work and not complain


            Output:



            Percent growth: 2.56235
            Percent growth: 0.90000
            Percent growth: No data yet





            share|improve this answer




















            • 1





              I love how hacky this is.

              – NoSplitSherlock
              Mar 1 at 19:02













            2












            2








            2







            You can use a ternary for the formatter as well - no need to stack 2 f-strings like Nikolas answer does:



            for pg in (2.562345678, 0.9, None): # 0.0 is also Falsy - careful ;o)
            print(f"Percent Growth: pg if pg else 'No data yet':'.05f' if pg else ''")
            # you need to put '.05f' into a string for this to work and not complain


            Output:



            Percent growth: 2.56235
            Percent growth: 0.90000
            Percent growth: No data yet





            share|improve this answer















            You can use a ternary for the formatter as well - no need to stack 2 f-strings like Nikolas answer does:



            for pg in (2.562345678, 0.9, None): # 0.0 is also Falsy - careful ;o)
            print(f"Percent Growth: pg if pg else 'No data yet':'.05f' if pg else ''")
            # you need to put '.05f' into a string for this to work and not complain


            Output:



            Percent growth: 2.56235
            Percent growth: 0.90000
            Percent growth: No data yet






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Mar 1 at 19:04

























            answered Mar 1 at 18:50









            Patrick ArtnerPatrick Artner

            25.9k62544




            25.9k62544







            • 1





              I love how hacky this is.

              – NoSplitSherlock
              Mar 1 at 19:02












            • 1





              I love how hacky this is.

              – NoSplitSherlock
              Mar 1 at 19:02







            1




            1





            I love how hacky this is.

            – NoSplitSherlock
            Mar 1 at 19:02





            I love how hacky this is.

            – NoSplitSherlock
            Mar 1 at 19:02

















            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%2f54949918%2fhow-to-apply-float-precision-type-specifier-in-a-conditional-f-string%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

            How to check contact read email or not when send email to Individual?

            Bahrain

            Postfix configuration issue with fips on centos 7; mailgun relay