How to apply float precision (type specifier) in a conditional f-string?How do I check if a string is a...

Why avoid shared user accounts?

Broken patches on a road

Every character has a name - does this lead to too many named characters?

Checking for the existence of multiple directories

Why is "points exist" not an axiom in geometry?

Why would the Pakistan airspace closure cancel flights not headed to Pakistan itself?

Is there any differences between "Gucken" and "Schauen"?

How should I handle players who ignore the session zero agreement?

Why did the villain in the first Men in Black movie care about Earth's Cockroaches?

How to acknowledge an embarrassing job interview, now that I work directly with the interviewer?

What to do when being responsible for data protection in your lab, yet advice is ignored?

Is there some relative to Dutch word "kijken" in German?

What to do if authors don't respond to my serious concerns about their paper?

How do you funnel food off a cutting board?

Eww, those bytes are gross

A universal method for left-hand alignment of a sequence of equalities

How do I say "Brexit" in Latin?

How would a Dictatorship make a country more successful?

Why did other German political parties disband so fast when Hitler was appointed chancellor?

Using only 1s, make 29 with the minimum number of digits

What makes the Forgotten Realms "forgotten"?

Word or phrase for showing great skill at something without formal training in it

How would an AI self awareness kill switch work?

Can I become debt free or should I file for bankruptcy? How do I manage my debt and finances?



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


How do I check if a string is a number (float)?How do I parse a string to a float or int in Python?How to determine a Python variable's type?How do I trim whitespace from a Python string?How to check if type of a variable is string?How to lowercase a string in Python?How to read a text file into a string variable and strip newlines?SQLAlchemy Turning Floats Into Strings in SQL?Dictionary true/false errorConvert float to string without scientific notation and false precision













8















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
















8















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














8












8








8








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









NoSplitSherlockNoSplitSherlock

1128




1128








  • 1





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

    – NoSplitSherlock
    12 hours ago














  • 1





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

    – NoSplitSherlock
    12 hours ago








1




1





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

– NoSplitSherlock
12 hours ago





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

– NoSplitSherlock
12 hours ago












3 Answers
3






active

oldest

votes


















9














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



















  • 1





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













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

    – NoSplitSherlock
    13 hours ago






  • 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
    13 hours ago






  • 1





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

    – Nikolas Stevenson-Molnar
    13 hours ago











  • @PatrickArtner Absolutely, that works too.

    – Nikolas Stevenson-Molnar
    13 hours ago



















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
    13 hours ago



















1














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























    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









    9














    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



















    • 1





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













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

      – NoSplitSherlock
      13 hours ago






    • 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
      13 hours ago






    • 1





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

      – Nikolas Stevenson-Molnar
      13 hours ago











    • @PatrickArtner Absolutely, that works too.

      – Nikolas Stevenson-Molnar
      13 hours ago
















    9














    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



















    • 1





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













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

      – NoSplitSherlock
      13 hours ago






    • 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
      13 hours ago






    • 1





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

      – Nikolas Stevenson-Molnar
      13 hours ago











    • @PatrickArtner Absolutely, that works too.

      – Nikolas Stevenson-Molnar
      13 hours ago














    9












    9








    9







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









    Nikolas Stevenson-MolnarNikolas Stevenson-Molnar

    1,246714




    1,246714








    • 1





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













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

      – NoSplitSherlock
      13 hours ago






    • 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
      13 hours ago






    • 1





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

      – Nikolas Stevenson-Molnar
      13 hours ago











    • @PatrickArtner Absolutely, that works too.

      – Nikolas Stevenson-Molnar
      13 hours ago














    • 1





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













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

      – NoSplitSherlock
      13 hours ago






    • 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
      13 hours ago






    • 1





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

      – Nikolas Stevenson-Molnar
      13 hours ago











    • @PatrickArtner Absolutely, that works too.

      – Nikolas Stevenson-Molnar
      13 hours ago








    1




    1





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







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















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

    – NoSplitSherlock
    13 hours ago





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

    – NoSplitSherlock
    13 hours ago




    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
    13 hours ago





    @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
    13 hours ago




    1




    1





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

    – Nikolas Stevenson-Molnar
    13 hours ago





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

    – Nikolas Stevenson-Molnar
    13 hours ago













    @PatrickArtner Absolutely, that works too.

    – Nikolas Stevenson-Molnar
    13 hours ago





    @PatrickArtner Absolutely, that works too.

    – Nikolas Stevenson-Molnar
    13 hours ago













    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
      13 hours ago
















    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
      13 hours ago














    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 13 hours ago

























    answered 13 hours ago









    Patrick ArtnerPatrick Artner

    24.9k62443




    24.9k62443








    • 1





      I love how hacky this is.

      – NoSplitSherlock
      13 hours ago














    • 1





      I love how hacky this is.

      – NoSplitSherlock
      13 hours ago








    1




    1





    I love how hacky this is.

    – NoSplitSherlock
    13 hours ago





    I love how hacky this is.

    – NoSplitSherlock
    13 hours ago











    1














    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




























      1














      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


























        1












        1








        1







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









        IdlehandsIdlehands

        5,6551620




        5,6551620






























            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

            Fairchild Swearingen Metro Inhaltsverzeichnis Geschichte | Innenausstattung | Nutzung | Zwischenfälle...

            Pilgersdorf Inhaltsverzeichnis Geografie | Geschichte | Bevölkerungsentwicklung | Politik | Kultur...

            Marineschifffahrtleitung Inhaltsverzeichnis Geschichte | Heutige Organisation der NATO | Nationale und...