10

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?

1
  • 1
    I formulated the question this way so it was clear no matter what condition it fails to even execute. Commented Mar 1, 2019 at 19:32

3 Answers 3

11

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.

Sign up to request clarification or add additional context in comments.

4 Comments

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 Isn't it strange though that I can format strings and use conditionals, but not both at the same time?
Image
@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.
Image
@PatrickArtner see the OP’s question and code sample. The if True is a stand in for any conditional.
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}")

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.