Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 889
NoSplitSherlock Avatar asked Mar 01 '19 17:03

NoSplitSherlock


2 Answers

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}")
like image 42
r.ook Avatar answered Oct 23 '22 14:10

r.ook


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.

like image 157
Nikolas Stevenson-Molnar Avatar answered Oct 23 '22 13:10

Nikolas Stevenson-Molnar