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.

Answer from Andras Deak -- Слава Україні on Stack Overflow
🌐
Reddit
reddit.com › r/learnpython › conditional statements inside f string
r/learnpython on Reddit: Conditional statements inside f String
March 31, 2023 -

Hello!

I am making an RPG-style adventure game with Python. It is nothing fancy, the entire game, combat, decisions are all done via the console.

The final boss unlocks the players ultimate ability and I am wondering if there is a cleaner way to code the following:

    def combat(player,enemies,ultimate=False):
        while True:
            if not ultimate:
                actions = [
                            f'Attack - Attack for 1d{player.attack}', 
                            f'Cast {player.spell_name}: Cost - 10 mana', 
                            f'Heal - Restore 1d10 + {player.spell_power//2}: Cost - 5 mana', 
                            f'Drink Mana Potion - Restore mana equal to 1d6 + {player.spell_power}'
                            # f'Use {player.ultimate if ultimate else ""}: Cost - {(player.mp//2) if player.name == "Paladin" else "None"}'
                        ]
            else:
                actions = [
                           f'Attack - Attack for 1d{player.attack}', 
                           f'Cast {player.spell_name}: 10 mana', 
                           f'Heal - Restore 1d10 + {player.spell_power//2}: 5 mana', 
                           f'Drink Mana Potion - Restore mana equal to 1d6 + {player.spell_power}', 
                           f'Use {player.ultimate}: {(player.mp//2) if player.name == "Paladin" else "No"} Mana'
                        ]

Currently have 2 separate but very similar lists with actions available to the player. The only difference is if the player has access to the ultimate ability. The commented out line is my attempt to display however it gives the following output when the combat sequence begins:

Choose your action:
1. Attack - Attack for 1d8
2. Cast Divine Storm: Cost - 10 mana
3. Heal - Restore 1d10 + 4: Cost - 5 mana
4. Drink Mana Potion - Restore mana equal to 1d6 + 8Use : Cost - 25

Thanks for the help, apologies if the format is off.

Discussions

python - f-strings formatter including for-loop or if conditions - Stack Overflow
You can't put a statement in an f string, only an expression. ... if ... More on stackoverflow.com
🌐 stackoverflow.com
python - conditional string in format string (f"{...}") - Stack Overflow
2 How to format a string in Python that when executed produces a valid if .. then .. else statement? More on stackoverflow.com
🌐 stackoverflow.com
python - How to implement conditional string formatting? - Stack Overflow
@HVS it is possible, see this answer on stringing together else/if statements to simulate an inline elif. But you really shouldn't, you should define a function instead. 2019-03-28T05:36:41.013Z+00:00 ... Note that you have to mix double " and single ' quotes because until Python 3.12, you ... More on stackoverflow.com
🌐 stackoverflow.com
January 15, 2020
formatting - Python conditional statements in f-string with format specifiers - Stack Overflow
You can keep the condition inside the f-string if you use two of them, the 2nd one for the a:.2f ... Sign up to request clarification or add additional context in comments. ... Find the answer to your question by asking. More on stackoverflow.com
🌐 stackoverflow.com
🌐
freeCodeCamp
freecodecamp.org › news › python-f-strings-tutorial-how-to-use-f-strings-for-string-formatting
Python f-String Tutorial – String Formatting in Python Explained with Code Examples
September 14, 2021 - Hence the conditional statement in the f-String is replaced with False. So far, you've only seen how to print values of variables, evaluate expressions, and use conditionals inside f-Strings.
🌐
Bobby Hadz
bobbyhadz.com › blog › python-f-string-conditional
Using f-string for conditional formatting in Python | bobbyhadz
Use a ternary operator to use f-strings for conditional formatting. The ternary operator will return the value to the left if the condition is met, otherwise, the value to the right is returned.
🌐
W3Schools
w3schools.com › python › python_string_formatting.asp
Python String Formatting
You can perform Python operations inside the placeholders. ... price = 59 tax = 0.25 txt = f"The price is {price + (price * tax)} dollars" print(txt) Try it Yourself » · You can perform if...else statements inside the placeholders:
🌐
Towards Data Science
towardsdatascience.com › home › latest › five wonderful uses of ‘f- strings’ in python
Five wonderful uses of 'f- Strings' in Python | Towards Data Science
January 22, 2025 - Lastly, f-strings are able to evaluate if-else conditions. You can specify the condition within the curly braces and it outputs the result.
Find elsewhere
🌐
Squash
squash.io › how-to-use-inline-if-statements-for-print-in-python
How to Use Inline If Statements for Print in Python - Squash Labs
November 25, 2023 - In this example, the inline if statement is used within the f-string to conditionally include the message "greater than 5" if x is greater than 5, or "less than or equal to 5" otherwise.
🌐
DataCamp
datacamp.com › tutorial › python-f-string
Python f-string: A Complete Guide | DataCamp
December 3, 2024 - You can use the ternary operator to make your string formatting respond to conditions. Let's start with some straightforward examples using the ternary operator: # Simple conditional formatting score = 85 print(f"Result: {'Pass' if score >= 70 else 'Fail'}") # Multiple conditions in data analysis value = 42 print(f"Status: {'High' if value > 75 else 'Medium' if value > 25 else 'Low'}")
🌐
DZone
dzone.com › coding › languages › efficient string formatting with python f-strings
Efficient String Formatting With Python f-Strings
January 2, 2024 - f-string simplifies string formatting, which provides a concise and readable way to embed expressions inside string literals.
🌐
Mimo
mimo.org › glossary › python › formatted-strings
Python Formatted Strings / f-string formatting Guide
In addition, f-strings allow for conditional logic, making it easy to tailor messages based on specific conditions or variables. ... order_total = 150 free_shipping_threshold = 100 shipping_status = "eligible" if order_total >= free_shipping_threshold else "not eligible" print(f"Your order is {shipping_status} for free shipping.")
🌐
Programiz
programiz.com › python-programming › fstring
Python f-string
If age is 18 or older, it outputs "an adult"; otherwise, it outputs "a minor". You can also access dictionary values directly within f-strings by using the dictionary key inside the curly braces {}.
🌐
datagy
datagy.io › home › python posts › python f-strings: everything you need to know!
Python f-strings: Everything you need to know! • datagy
December 20, 2022 - Learn how to use Python f-strings including using conditions, formatting values, aligning values, and debugging. A video tutorial is included!
🌐
GeeksforGeeks
geeksforgeeks.org › python › formatted-string-literals-f-strings-python
f-strings in Python - GeeksforGeeks
May 16, 2026 - Triple quotes allow quotes to be used easily inside strings. Example 3: This example evaluates an expression directly inside an f-string.
🌐
Bentley
cissandbox.bentley.edu › sandbox › wp-content › uploads › 2022-02-10-Documentation-on-f-strings-Updated.pdf pdf
A Guide to Formatting with f-strings in Python - CIS Sandbox
the f-string to help delineate the spacing. That number after the ":"will cause that field to be · that number of characters wide. The first line in the print() statement using f-strings is an
🌐
Real Python
realpython.com › python-f-strings
Python's F-String for String Interpolation and Formatting – Real Python
November 30, 2024 - For example, you may have a hundred debugging messages but only ten warning messages in your code. If you use an f-string or the .format() method to construct your logging messages, then Python will interpolate all the strings regardless of the logging level that you’ve chosen.