How to implement conditional string formatting?

Solution 1:

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.

Solution 2:

On Python 3.6+, use a formatted string literal (they're called f-strings: f"{2+2}" produces "4") with an if statement:

print(f"Shut the door{'s' if abs(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. (You can still use backslashes in the outer part of an f-string, eg. f'{2}\n' is fine)

Solution 3:

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]