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.
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.
Conditional statements inside f String
python - advanced string formatting vs template strings - Stack Overflow
Is there a way to add a conditional string in Python's advance string formatting "foo {}".format(bar)? - Stack Overflow
Create a conditional expression that evaluates to string "negative" if user\_val is less than 0, and "nonnegative" otherwise. Sample output with input: -9 -9 is negative
Videos
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.
One key advantage of string templates is that you can substitute only some of the placeholders using the safe_substitute method. Normal format strings will raise an error if a placeholder is not passed a value. For example:
"Hello, {first} {last}".format(first='Joe')
raises:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'last'
But:
from string import Template
Template("Hello, $first $last").safe_substitute(first='Joe')
Produces:
'Hello, Joe $last'
Note that the returned value is a string, not a Template; if you want to substitute the $last you'll need to create a new Template object from that string.
Templates are meant to be simpler than the the usual string formatting, at the cost of expressiveness. The rationale of PEP 292 compares templates to Python's %-style string formatting:
Python currently supports a string substitution syntax based on C's
printf()'%' formatting character. While quite rich, %-formatting codes are also error prone, even for experienced Python programmers. A common mistake is to leave off the trailing format character, e.g. thesin%(name)s.In addition, the rules for what can follow a % sign are fairly complex, while the usual application rarely needs such complexity. Most scripts need to do some string interpolation, but most of those use simple "stringification" formats, i.e.
%sor%(name)sThis form should be made simpler and less error prone.
While the new .format() improved the situation, it's still true that the format string syntax is rather complex, so the rationale still has its points.