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.

Answer from DSM on Stack Overflow
๐ŸŒ
Towards Data Science
towardsdatascience.com โ€บ home โ€บ latest โ€บ python template string formatting method
Python Template String Formatting Method | Towards Data Science
January 21, 2025 - >>> d = dict(obj='Car') >>> Template('$obj is red').substitute(d) 'Car is red' If there is an invalid string after the placeholder, only the placeholder is considered. Example, see the โ€˜.โ€™ (dot) after $who.
Discussions

Conditional statements inside f String
Can this be cleaner? Certainly. def combat(player, enemies, ultimate=False): 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}' ] if ultimate: actions.append( f'Use {player.ultimate}: {player.mp // 2 if player.name == "Paladin" else "No"} Mana' ) while True: ... How's that? More on reddit.com
๐ŸŒ r/learnpython
5
1
March 31, 2023
python - advanced string formatting vs template strings - Stack Overflow
I was wondering if there is a advantage of using template strings instead of the new advanced string formatting? More on stackoverflow.com
๐ŸŒ stackoverflow.com
Is there a way to add a conditional string in Python's advance string formatting "foo {}".format(bar)? - Stack Overflow
For example I have a line of code like this if checked: checked_string = "check" else: checked_string = "uncheck" print "You can {} that step!".format(checked_string) Is there a shortcut to More on stackoverflow.com
๐ŸŒ stackoverflow.com
April 13, 2012
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
Get rid of line 2 (cond_str = input()). It serves no purpose. More on reddit.com
๐ŸŒ r/learnpython
6
2
November 2, 2023
๐ŸŒ
Medium
medium.com โ€บ @bluebirz โ€บ 3-ways-for-python-string-template-71d2bb5d3de1
3 ways for Python string template | by bluebirz | Medium
January 28, 2025 - In short, we can use this library to design string formatting with more complex conditions. But for this blog we make just an intro for this. Start from install this library, pip install jinja2. And use it like this. With .render() we supply the parameter variables specified in {{}} in the template. Parameters can be either keywords or dict of key-value pairs. Python ยท
๐ŸŒ
Python
docs.python.org โ€บ 3 โ€บ library โ€บ string.html
string โ€” Common string operations
Performs the template substitution, returning a new string. mapping is any dictionary-like object with keys that match the placeholders in the template. Alternatively, you can provide keyword arguments, where the keywords are the placeholders.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ template-class-in-python
String Template Class in Python - GeeksforGeeks
July 23, 2025 - Explanation: This code creates a template with placeholders $name and $marks. It loops through a list of student tuples, replacing the placeholders with each student's name and marks using substitute. Example 3: In this example, we use safe_substitute to avoid errors when some placeholders have no corresponding value. ... from string import Template t = Template('$name is the $job of $company') s = t.safe_substitute(name='Raju Kumar', job='TCE') print(s)
๐ŸŒ
Stack Abuse
stackabuse.com โ€บ formatting-strings-with-the-python-template-class
Formatting Strings with the Python Template Class
September 19, 2021 - It's a viable alternative to other to the built-in string substitution options when it comes to creating complex string-based templates. In this article, we've learned how the Python Template class works. We also learned about the more common errors that we can introduce when using Template and how to work around them. Finally, we covered how to customize the class through subclassing and how to use it to run Python code. With this knowledge at hand, we're in a better condition to effectively use the Python Template class to perform string interpolation or substitution in our code.
๐ŸŒ
Real Python
realpython.com โ€บ python-t-strings
Python 3.14: Template Strings (T-Strings) โ€“ Real Python
May 30, 2025 - In t-strings, Python eagerly evaluates expressions inside placeholders when it creates the template. However, in some scenarios, such as logging, caching, or conditional rendering, you might need to delay the evaluation of expressions until theyโ€™re needed.
Find elsewhere
๐ŸŒ
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.

๐ŸŒ
Real Python
realpython.com โ€บ python-string-formatting
Python String Formatting: Available Tools and Their Features โ€“ Real Python
December 2, 2024 - The different types of string formatting in Python include f-strings for embedding expressions inside string literals, the .format() method for creating string templates and filling them with values, and the modulo operator (%), an older method used in legacy code similar to Cโ€™s printf() function.
๐ŸŒ
Python
peps.python.org โ€บ pep-0750
PEP 750 โ€“ Template Strings - Python Enhancement Proposals
July 8, 2024 - When developers explicitly construct an Interpolation, they may optionally provide a value for the expression attribute. Even though it is stored as a string, this should be a valid Python expression. If no value is provided, the expression attribute defaults to the empty string (""). We expect that the expression attribute will not be used in most template processing code.
๐ŸŒ
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.
๐ŸŒ
Jinja
jinja.palletsprojects.com โ€บ en โ€บ stable โ€บ templates
Template Designer Documentation โ€” Jinja Documentation (3.1.x)
String literals in templates with automatic escaping are considered unsafe because native Python strings are not safe. A control structure refers to all those things that control the flow of a program - conditionals (i.e. if/elif/else), for-loops, as well as things like macros and blocks.
๐ŸŒ
Python
docs.python.org โ€บ 3 โ€บ library โ€บ string.templatelib.html
string.templatelib โ€” Support for template string literals
While literal syntax is the most common way to create a Template, it is also possible to create them directly using the constructor: >>> from string.templatelib import Interpolation, Template >>> cheese = 'Camembert' >>> template = Template( ... 'Ah! We do have ', Interpolation(cheese, 'cheese'), '.' ...
๐ŸŒ
Python
peps.python.org โ€บ pep-3101
PEP 3101 โ€“ Advanced String Formatting | peps.python.org
It is exposed as a separate function for cases where you want to pass in a predefined dictionary of arguments, rather than unpacking and repacking the dictionary as individual arguments using the *args and **kwds syntax. โ€˜vformatโ€™ does the work of breaking up the format template string into character data and replacement fields.
Top answer
1 of 6
41

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.

2 of 6
29

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. the s in %(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. %s or %(name)s This 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.

๐ŸŒ
Python.org
discuss.python.org โ€บ peps
PEP750: Template Strings (new updates) - Page 8 - PEPs - Discussions on Python.org
April 14, 2025 - Hi all, Thank you again for all the helpful feedback on PEP 750! Weโ€™ve just posted a PR with a set of updates based on that feedback. You can read the updated PEP 750 here. Some key updates include: Introduction of โ€ฆ
๐ŸŒ
Tutorialspoint
tutorialspoint.com โ€บ python โ€บ using_string_template_class.htm
Python - String Template Class
from string import Template temp_str = "My name is $name and I am $age years old" tempobj = Template(temp_str) ret = tempobj.substitute(name='Rajesh', age=23) print (ret) ... We can also unpack the key-value pairs from a dictionary to substitute the values. from string import Template student = {'name':'Rajesh', 'age':23} temp_str = "My name is $name and I am $age years old" tempobj = Template(temp_str) ret = tempobj.substitute(**student) print (ret)
๐ŸŒ
Python Cheatsheet
pythoncheatsheet.org โ€บ home โ€บ string formatting
Python String Formatting - Python Cheatsheet
A simpler and less powerful mechanism, but it is recommended when handling strings generated by users. Due to their reduced complexity, template strings are a safer choice.