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 OverflowYou 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.
I would recommend that you actually separate the fstring into two lines
num_str = f'{num:.2f}' if ppl else f'{num}'
final_str = f'I am {num_str}'
That way each line is as simple as it can be.
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.
python - f-strings formatter including for-loop or if conditions - Stack Overflow
python - conditional string in format string (f"{...}") - Stack Overflow
python - How to implement conditional string formatting? - Stack Overflow
formatting - Python conditional statements in f-string with format specifiers - Stack Overflow
Videos
str(None) is not None, but "None". So without that useless and harmful stringification:
foo = "soner test " \
f"{str(obj['my_str_index']) if obj['my_str_index'] is not None else 'null'}"
EDIT: A more legible way (note that interpolation in an f-string automatically stringifies, so we don't need str at all):
index = obj['my_str_index']
if index is None:
index = "none"
foo = f"soner test {index}"
EDIT: Another way, with the walrus (limited to 3.8+):
foo = f"soner test {'null' if (index := obj['my_str_index']) is None else index}"
You can greatly simplify the condition. This will work (in most cases, see the caveat below) and in my opinion a bit more readable
foo = f"soner test {obj['my_str_index'] or 'null'}"
You don't have to worry about str(...) because the interpolation mechanism calls the objects __str__ method implicitly (if it does not have __format__).
The only caveat with this approach is that foo will contain null if obj['my_str_index'] is any of the falsey values (None, 0 and any empty sequence).
Your code actually is valid Python if you remove two characters, the comma and the colon.
>>> gender= "male"
>>> print "At least, that's what %s told me." %("he" if gender == "male" else "she")
At least, that's what he told me.
More modern style uses .format, though:
>>> s = "At least, that's what {pronoun} told me.".format(pronoun="he" if gender == "male" else "she")
>>> s
"At least, that's what he told me."
where the argument to format can be a dict you build in whatever complexity you like.
Use an f-string:
plural = ''
if num_doors != 1:
plural = 's'
print(f'Shut the door{plural}.')
Or in one line with a conditional expression (a one-line version of the if/else statement):
print(f'Shut the door{"s" if num_doors != 1 else ""}.')
Note that you have to mix double " and single ' quotes because until Python 3.12, you can't use backslashes to escape quotes in the expression part of an f-string. You can still use backslashes in the outer part of an f-string, so f'{2+2}\n' is fine.
Hello i am a very very beginner coder. I’m in a beginner python class and I feel like the text books just throws stuff at concepts. Why are f’strings important? If I’m understanding it right I feel like the same output could get accomplished in a different way.