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.

🌐
DZone
dzone.com › coding › languages › efficient string formatting with python f-strings
Efficient String Formatting With Python f-Strings
January 2, 2024 - ... In the example above, .2f specifies that the floating-point number should be formatted with two decimal places. We can use the ternary operator inside the f-strings for evaluating conditional expressions.
🌐
Bobby Hadz
bobbyhadz.com › blog › python-f-string-conditional
Using f-string for conditional formatting in Python | bobbyhadz
The ternary operator will return the value to the left if the condition is met, otherwise, the value to the right is returned. ... Copied!my_str = 'bobbyhadz.com' # ✅ f-string formatting with a condition result = f'Result: {my_str.upper() ...
🌐
Be A Python Dev
beapython.dev › 2020 › 05 › 09 › python-palindrome-detection-f-strings-ternary-operators-and-fast-fail-optimizations
Python Palindrome Detection, F Strings, Ternary Operators, and Fail Fast Optimizations – Be A Python Dev
September 11, 2020 - Ah, much simpler! To achieve this we utilize the splicing notation, F strings which are fast formatted strings, and a ternary operator to simplify our logic check, and reduce line usage to be able to visually process longer code in one screen.
🌐
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 - ▶ Let's take a simple example using the ternary operator. Given a number num, you'd like to check if it's even. You know that a number is even if it's evenly divisible by 2. Let's use this to write our expression, as shown below: num = 87; print(f"Is num even? {True if num%2==0 else False}") ... If the condition is True, you just return True indicating that num is indeed even, and False otherwise.
🌐
GeeksforGeeks
geeksforgeeks.org › ternary-operator-in-python
Ternary Operator in Python - GeeksforGeeks
The ternary operator in Python allows us to perform conditional checks and assign values or perform operations on a single line. It is also known as a conditional expression because it evaluates a condition and returns one value if the condition ...
Published   December 18, 2024
🌐
Martin Heinz
martinheinz.dev › blog › 70
Python f-strings Are More Powerful Than You Might Think | Martin Heinz | Personal Website & Blog
April 4, 2022 - Building on top of the above example with nested f-strings, we can go a bit farther and use ternary conditional operators inside the inner f-string:
🌐
Medium
medium.com › @milansojitra1019 › unlocking-the-power-of-f-string-in-python-practical-examples-and-application-5c5e998f612b
Unlocking the Power of f-String in Python: Practical Examples and Application | by Milan Sojitra | Medium
June 1, 2024 - Explanation: This example uses a conditional expression (ternary operator) within an f-string to dynamically choose between “old” and “young” based on the value of age.
Find elsewhere
🌐
Mimo
mimo.org › glossary › python › ternary-operator
Python Ternary Operator: Syntax, Usage, and Examples
Assignment inside expressions: Don’t try to assign and return from the same ternary in multiple steps. Python doesn’t allow assignment expressions like JavaScript does. ... Each case allows you to replace bulky conditional logic with one clear, compact line. The Python ternary operator gives you a flexible and readable way to handle conditional assignments and expressions.
🌐
Vocal Media
vocal.media › education › mastering-python-f-strings-unleashing-the-power-and-tricks-of-dynamic-string-formatting
Mastering Python F-Strings: Unleashing the Power and Tricks of Dynamic String Formatting | Education
Dictionary Access: F-strings allow ... · Expressions and Control Flow: Include conditional statements or expressions within f-strings by using ternary operators or calling functions....
🌐
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 - F-strings allows you to put expressions between the brackets. The expression within the brackets is evaluated and displayed as a result. Here the distance is calculated within the expression and this saves an additional step for the user.
🌐
DataCamp
datacamp.com › tutorial › python-f-string
Python f-string: A Complete Guide | DataCamp
December 3, 2024 - # Basic string formatting comparison import timeit name = "Python" version = 3.9 # Using + operator (slowest for multiple items) def concat_plus(): return "Running " + name + " version " + str(version) # Using % formatting (old style) def format_percent(): return "Running %s version %s" % (name, version) # Using str.format() def format_method(): return "Running {} version {}".format(name, version) # Using f-string def format_fstring(): return f"Running {name} version {version}" # Let's time each method print("Time taken (microseconds):") print(f"+ operator: {timeit.timeit(concat_plus, number=100000):.2f}") print(f"% operator: {timeit.timeit(format_percent, number=100000):.2f}") print(f"str.format: {timeit.timeit(format_method, number=100000):.2f}") print(f"f-string: {timeit.timeit(format_fstring, number=100000):.2f}")
🌐
Python Tutorial
pythontutorial.net › home › python basics › python ternary operator
Python Ternary Operator
March 26, 2025 - Here’s the basic syntax of ternary operator in Python: value_if_true if condition else value_if_falseCode language: Python (python)
🌐
DevToolbox
devtoolbox.dedyn.io › home › blog › python string formatting & f-strings: the complete guide for 2026
Python String Formatting & F-Strings: The Complete Guide for 2026 | DevToolbox Blog
2 weeks ago - Yes, f-strings support any valid Python expression including dictionary access, method calls, list comprehensions, ternary operators, and function calls. For dictionaries, use different quote types inside and outside: f"{user['name']}" inside ...
🌐
Flexiple
flexiple.com › python › python-ternary
Python ternary operators - How to use them? - Flexiple Tutorials - Flexiple
Learn how to use Python ternary operators efficiently with examples and explanations. Master this concise syntax for conditional expressions.
🌐
Hacker News
news.ycombinator.com › item
Python 3's F-Strings: An Improved String Formatting Syntax | Hacker News
January 27, 2021 - name = 'world' print(f'hello {name.upper()=}') outputs: · hello name.upper()='WORLD' It's small, but very useful in debugging an issue or logging something to the console
🌐
Python Tips
book.pythontips.com › en › latest › ternary_operators.html
6. Ternary Operators — Python Tips 0.1 documentation
Syntax was introduced in Python 2.5 and can be used in python 2.5 or greater. ... The first statement (True or “Some”) will return True and the second statement (False or “Some”) will return Some. This is helpful in case where you quickly want to check for the output of a function and give a useful message if the output is empty: >>> output = None >>> msg = output or "No data returned" >>> print(msg) No data returned · Or as a simple way to define function parameters with dynamic default values: