I\'ve been working on a text-based game in Python, and I\'ve come across an instance where I want to format a string differently based on a set of conditions.
Speci
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)
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]
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.