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)