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.

Leave a Comment