Formatting Strings Cheat Sheet
Old string formatting (Optional)
The format() method was introduced in Python 2.6. Before that, the % (modulo) operator could be used to get a similar result. While this method is no longer recommended for new code, you might come across it in someone else’s code. This is what it looks like:
“base string with %s placeholder” % variable
The % (modulo) operator returns a copy of the string where the placeholders indicated by % followed by a formatting expression are replaced by the variables after the operator.
“base string with %d and %d placeholders” % (value1, value2)
To replace more than one value, the values need to be written between parentheses. The formatting expression needs to match the value type.
“%(var1) %(var2)” % {var1:value1, var2:value2}
Variables can be replaced by name using a dictionary syntax (we’ll learn about dictionaries in an upcoming video).
“Item: %s — Amount: %d — Price: %.2f” % (item, amount, price)
The formatting expressions are mostly the same as those of the format() method.
Check out the official documentation for old string formatting.
Formatted string literals (Optional)
This feature was added in Python 3.6 and isn’t used a lot yet. Again, it’s included here in case you run into it in the future, but it’s not needed for this or any upcoming courses.
A formatted string literal or f-string is a string that starts with ‘f’ or ‘F’ before the quotes. These strings might contain {} placeholders using expressions like the ones used for format method strings.
The important difference with the format method is that it takes the value of the variables from the current context, instead of taking the values from parameters.
Examples:
>>> name = “Micah”
>>> print(f’Hello {name}’)
Hello Micah
>>> item = “Purple Cup”
>>> amount = 5
>>> price = amount * 3.25
>>> print(f’Item: {item} — Amount: {amount} — Price: {price:.2f}’)
Item: Purple Cup — Amount: 5 — Price: 16.25
Check out the official documentation for f-strings.