2.0 Python f-strings#
In the first notebook you learned to use print() to display text and variables. But the print statements can get long if you want to show many variables at once. For example:
a = 2
b = 7
print('a is', a, 'and b is', b, '. Their product is', a*b, '.')
Also you don’t have full control over the spacing, e.g. the space added before the '.' after the value of b. There is a more convenient way to print variables:
print(f'a is {a} and b is {b}. Their product is {a*b}.')
The string inside print() starts with f’ and ends with a normal ’. This type of string is called an “f-string”, and it has special powers: it can contain variables and python code inside curly brackets { }. Using f-strings is often more convenient than piecing together a print statement with a list of strings and variables.
One more useful property of f-strings is that you can control how many decimal digits are printed for floating point numbers. After the variable but inside the brackets, type a colon followed by a formatting code. There are several such codes, for now we’ll show only one: .2f.
Here .2 means two digits after the decimal point, and f specifies that the data to be printed is a floating point number.
e = 2.71828182846
print(f'e is {e}.')
print(f'e with two decimals is {e:.2f}.')
For your easy reference, please see below some of the formatting codes you could use to format a variable within an f-string.
Format Code |
Description |
Example Usage |
Output |
|---|---|---|---|
|
Formats a float to 2 decimal places |
|
|
|
Formats an integer |
|
|
|
Pads an integer with leading zeros to make it 8 digits |
|
|
|
Formats a number as a percentage with 1 decimal place |
|
|
|
Formats a number in scientific notation (lowercase) |
|
|
|
Formats a number in scientific notation (uppercase) |
|
|
|
Formats an integer as a hexadecimal (lowercase) |
|
|
|
Formats an integer as a hexadecimal (uppercase) |
|
|
|
Formats an integer as binary |
|
|
|
Formats an integer as octal |
|
|
|
Centers a string within 10 spaces |
|
|
|
Left-aligns a string within 10 spaces |
|
|
|
Right-aligns a string within 10 spaces |
|
|
|
Left-aligns a string within 10 custom characters (here |
|
|
|
Right-aligns a string within 10 custom characters (here |
|
|
|
Adds commas as thousand separators |
|
|
|
Adds underscores as thousand separators |
|
|