Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using f-string with format depending on a condition

How can I use f-string with logic to format an int as a float? I would like if ppl is True to format num to 2 decimal places, and if ppl is False to rformat it as whatever it is.

Something like string = f'i am {num:.2f if ppl else num}' but this does not work. The below code demonstrates the behaviour that I want to achieve with a simpler f-string if possible:

ppl = True num = 3 string = f'I am {num:.2f}' if ppl else f'I am {num}' print(string) #if ppl False #=> i am 3 #if ppl True #=> i am 3.00 
like image 704
jacobcan118 Avatar asked Aug 16 '18 22:08

jacobcan118


People also ask

How do you use f-string and format or replacement operator in Python?

To create an f-string, prefix the string with the letter “ f ”. The string itself can be formatted in much the same way that you would with str. format(). F-strings provide a concise and convenient way to embed python expressions inside string literals for formatting.

Can you use functions in F strings?

f strings can also support functions or any other expression, evaluated inside the string.

Can you use an F-string in a variable?

If you have multiple variables in the string, you need to enclose each of the variable names inside a set of curly braces. The syntax is shown below: f"This is an f-string {var_name} and {var_name}." ▶ Here's an example.

Is F-string faster than format?

f-strings are faster than both %-formatting and str. format() . At runtime, each expression inside the curly braces gets evaluated within its own scope, and then it's put together into the final string.


Video Answer


2 Answers

You can nest expressions to evaluate inside expressions in an f-string. This means you can move the ternary right inside your f-string:

string = f'I am {num:{".2f" if ppl else ""}}' 

Note the additional pair of braces needed for nesting.

But I don't think this is cleaner. Personally I find it harder to parse what's going on here, as opposed to your clear original version. After all simple is better than complex; flat is better than nested.

like image 63

I would recommend that you actually separate the fstring into two lines

num_str = f'{num:.2f}' if ppl else f'{num}' str = f'I am {num_str}' 

That way each line is as simple as it can be.

like image 33
Gamrix Avatar answered Oct 08 '22 13:10

Gamrix