How to implement conditional string formatting?
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.
There is a conditional expression in Python which takes the form:
A if condition else B
Your example can easily be turned into valid Python by omitting just two characters:
print ("At least, that's what %s told me." %
("he" if gender == "male" else "she"))
An alternative I'd often prefer is to use a dictionary:
pronouns = {"female": "she", "male": "he"}
print "At least, that's what %s told me." % pronouns[gender]
On Python 3.6+, use an f-string with a conditional expression (a one-line version of the if
/else
statement):
print(f'Shut the door{"s" if num_doors != 1 else ""}.')
You can't use backslashes to escape quotes in the expression part of an f-string so
you have to mix double "
and single '
quotes. To be clear, you can still use backslashes in the outer part of an f-string, so f'{2+2}\n'
is fine.